es6.js 4.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. var finalVertexCode;
  143. this._loadVertexShaderAsync(vertexSource)
  144. .then(function (vertexCode) {
  145. return _this._processIncludesAsync(vertexCode);
  146. })
  147. .then(function (vertexCodeWithIncludes) {
  148. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  149. return _this._loadFragmentShaderAsync(fragmentSource);
  150. })
  151. .then(function (fragmentCode) {
  152. return _this._processIncludesAsync(fragmentCode);
  153. })
  154. .then(function (fragmentCodeWithIncludes) {
  155. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  156. if (baseName) {
  157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  159. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  160. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  161. }
  162. else {
  163. _this._vertexSourceCode = finalVertexCode;
  164. _this._fragmentSourceCode = migratedFragmentCode;
  165. }
  166. _this._prepareEffect();
  167. });
  168. }
  169. Object.defineProperty(Effect.prototype, "key", {
  170. get: function () {
  171. return this._key;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. // Properties
  177. Effect.prototype.isReady = function () {
  178. return this._isReady;
  179. };
  180. Effect.prototype.getEngine = function () {
  181. return this._engine;
  182. };
  183. Effect.prototype.getProgram = function () {
  184. return this._program;
  185. };
  186. Effect.prototype.getAttributesNames = function () {
  187. return this._attributesNames;
  188. };
  189. Effect.prototype.getAttributeLocation = function (index) {
  190. return this._attributes[index];
  191. };
  192. Effect.prototype.getAttributeLocationByName = function (name) {
  193. var index = this._attributesNames.indexOf(name);
  194. return this._attributes[index];
  195. };
  196. Effect.prototype.getAttributesCount = function () {
  197. return this._attributes.length;
  198. };
  199. Effect.prototype.getUniformIndex = function (uniformName) {
  200. return this._uniformsNames.indexOf(uniformName);
  201. };
  202. Effect.prototype.getUniform = function (uniformName) {
  203. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  204. };
  205. Effect.prototype.getSamplers = function () {
  206. return this._samplers;
  207. };
  208. Effect.prototype.getCompilationError = function () {
  209. return this._compilationError;
  210. };
  211. // Methods
  212. Effect.prototype.executeWhenCompiled = function (func) {
  213. if (this.isReady()) {
  214. func(this);
  215. return;
  216. }
  217. this.onCompileObservable.add(function (effect) {
  218. func(effect);
  219. });
  220. };
  221. /** @ignore */
  222. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  223. if (BABYLON.Tools.IsWindowObjectExist()) {
  224. // DOM element ?
  225. if (vertex instanceof HTMLElement) {
  226. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  227. return Promise.resolve(vertexCode);
  228. }
  229. }
  230. // Base64 encoded ?
  231. if (vertex.substr(0, 7) === "base64:") {
  232. var vertexBinary = window.atob(vertex.substr(7));
  233. return Promise.resolve(vertexBinary);
  234. }
  235. // Is in local store ?
  236. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  237. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  238. }
  239. var vertexShaderUrl;
  240. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  241. vertexShaderUrl = vertex;
  242. }
  243. else {
  244. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  245. }
  246. // Vertex shader
  247. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  248. };
  249. /** @ignore */
  250. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  251. if (BABYLON.Tools.IsWindowObjectExist()) {
  252. // DOM element ?
  253. if (fragment instanceof HTMLElement) {
  254. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  255. return Promise.resolve(fragmentCode);
  256. }
  257. }
  258. // Base64 encoded ?
  259. if (fragment.substr(0, 7) === "base64:") {
  260. var fragmentBinary = window.atob(fragment.substr(7));
  261. return Promise.resolve(fragmentBinary);
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  266. }
  267. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  268. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  269. }
  270. var fragmentShaderUrl;
  271. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  272. fragmentShaderUrl = fragment;
  273. }
  274. else {
  275. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  276. }
  277. // Fragment shader
  278. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  279. };
  280. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  281. // Rebuild shaders source code
  282. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  283. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  284. vertexCode = prefix + vertexCode;
  285. fragmentCode = prefix + fragmentCode;
  286. // Number lines of shaders source code
  287. var i = 2;
  288. var regex = /\n/gm;
  289. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  290. i = 2;
  291. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. // Dump shaders name and formatted source code
  293. if (this.name.vertexElement) {
  294. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  295. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  296. }
  297. else if (this.name.vertex) {
  298. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  299. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  300. }
  301. else {
  302. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  303. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  304. }
  305. };
  306. ;
  307. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  308. var preparedSourceCode = this._processPrecision(sourceCode);
  309. if (this._engine.webGLVersion == 1) {
  310. return preparedSourceCode;
  311. }
  312. // Already converted
  313. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  314. return preparedSourceCode.replace("#version 300 es", "");
  315. }
  316. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  317. // Remove extensions
  318. // #extension GL_OES_standard_derivatives : enable
  319. // #extension GL_EXT_shader_texture_lod : enable
  320. // #extension GL_EXT_frag_depth : enable
  321. // #extension GL_EXT_draw_buffers : require
  322. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  323. var result = preparedSourceCode.replace(regex, "");
  324. // Migrate to GLSL v300
  325. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  326. result = result.replace(/attribute[ \t]/g, "in ");
  327. result = result.replace(/[ \t]attribute/g, " in");
  328. if (isFragment) {
  329. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  330. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  331. result = result.replace(/texture2D\s*\(/g, "texture(");
  332. result = result.replace(/textureCube\s*\(/g, "texture(");
  333. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  334. result = result.replace(/gl_FragColor/g, "glFragColor");
  335. result = result.replace(/gl_FragData/g, "glFragData");
  336. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  337. }
  338. return result;
  339. };
  340. Effect.prototype._processIncludesAsync = function (sourceCode) {
  341. var _this = this;
  342. return new Promise(function (resolve, reject) {
  343. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  344. var match = regex.exec(sourceCode);
  345. var returnValue = sourceCode;
  346. while (match != null) {
  347. var includeFile = match[1];
  348. // Uniform declaration
  349. if (includeFile.indexOf("__decl__") !== -1) {
  350. includeFile = includeFile.replace(/__decl__/, "");
  351. if (_this._engine.supportsUniformBuffers) {
  352. includeFile = includeFile.replace(/Vertex/, "Ubo");
  353. includeFile = includeFile.replace(/Fragment/, "Ubo");
  354. }
  355. includeFile = includeFile + "Declaration";
  356. }
  357. if (Effect.IncludesShadersStore[includeFile]) {
  358. // Substitution
  359. var includeContent = Effect.IncludesShadersStore[includeFile];
  360. if (match[2]) {
  361. var splits = match[3].split(",");
  362. for (var index = 0; index < splits.length; index += 2) {
  363. var source = new RegExp(splits[index], "g");
  364. var dest = splits[index + 1];
  365. includeContent = includeContent.replace(source, dest);
  366. }
  367. }
  368. if (match[4]) {
  369. var indexString = match[5];
  370. if (indexString.indexOf("..") !== -1) {
  371. var indexSplits = indexString.split("..");
  372. var minIndex = parseInt(indexSplits[0]);
  373. var maxIndex = parseInt(indexSplits[1]);
  374. var sourceIncludeContent = includeContent.slice(0);
  375. includeContent = "";
  376. if (isNaN(maxIndex)) {
  377. maxIndex = _this._indexParameters[indexSplits[1]];
  378. }
  379. for (var i = minIndex; i < maxIndex; i++) {
  380. if (!_this._engine.supportsUniformBuffers) {
  381. // Ubo replacement
  382. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  383. return p1 + "{X}";
  384. });
  385. }
  386. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  387. }
  388. }
  389. else {
  390. if (!_this._engine.supportsUniformBuffers) {
  391. // Ubo replacement
  392. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  393. return p1 + "{X}";
  394. });
  395. }
  396. includeContent = includeContent.replace(/\{X\}/g, indexString);
  397. }
  398. }
  399. // Replace
  400. returnValue = returnValue.replace(match[0], includeContent);
  401. }
  402. else {
  403. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  404. _this._engine._loadFileAsync(includeShaderUrl)
  405. .then(function (fileContent) {
  406. Effect.IncludesShadersStore[includeFile] = fileContent;
  407. return _this._processIncludesAsync(returnValue);
  408. })
  409. .then(function (returnValue) {
  410. resolve(returnValue);
  411. });
  412. return;
  413. }
  414. match = regex.exec(sourceCode);
  415. }
  416. resolve(returnValue);
  417. });
  418. };
  419. Effect.prototype._processPrecision = function (source) {
  420. if (source.indexOf("precision highp float") === -1) {
  421. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  422. source = "precision mediump float;\n" + source;
  423. }
  424. else {
  425. source = "precision highp float;\n" + source;
  426. }
  427. }
  428. else {
  429. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  430. source = source.replace("precision highp float", "precision mediump float");
  431. }
  432. }
  433. return source;
  434. };
  435. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  436. var _this = this;
  437. this._isReady = false;
  438. this._vertexSourceCodeOverride = vertexSourceCode;
  439. this._fragmentSourceCodeOverride = fragmentSourceCode;
  440. this.onError = function (effect, error) {
  441. if (onError) {
  442. onError(error);
  443. }
  444. };
  445. this.onCompiled = function () {
  446. var scenes = _this.getEngine().scenes;
  447. for (var i = 0; i < scenes.length; i++) {
  448. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  449. }
  450. if (onCompiled) {
  451. onCompiled(_this._program);
  452. }
  453. };
  454. this._fallbacks = null;
  455. this._prepareEffect();
  456. };
  457. Effect.prototype.getSpecificUniformLocations = function (names) {
  458. var engine = this._engine;
  459. return engine.getUniforms(this._program, names);
  460. };
  461. Effect.prototype._prepareEffect = function () {
  462. var attributesNames = this._attributesNames;
  463. var defines = this.defines;
  464. var fallbacks = this._fallbacks;
  465. this._valueCache = {};
  466. var previousProgram = this._program;
  467. try {
  468. var engine = this._engine;
  469. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  470. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  471. }
  472. else {
  473. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  474. }
  475. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  476. if (engine.supportsUniformBuffers) {
  477. for (var name in this._uniformBuffersNames) {
  478. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  479. }
  480. }
  481. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  482. this._attributes = engine.getAttributes(this._program, attributesNames);
  483. var index;
  484. for (index = 0; index < this._samplers.length; index++) {
  485. var sampler = this.getUniform(this._samplers[index]);
  486. if (sampler == null) {
  487. this._samplers.splice(index, 1);
  488. index--;
  489. }
  490. }
  491. engine.bindSamplers(this);
  492. this._compilationError = "";
  493. this._isReady = true;
  494. if (this.onCompiled) {
  495. this.onCompiled(this);
  496. }
  497. this.onCompileObservable.notifyObservers(this);
  498. this.onCompileObservable.clear();
  499. // Unbind mesh reference in fallbacks
  500. if (this._fallbacks) {
  501. this._fallbacks.unBindMesh();
  502. }
  503. if (previousProgram) {
  504. this.getEngine()._deleteProgram(previousProgram);
  505. }
  506. }
  507. catch (e) {
  508. this._compilationError = e.message;
  509. // Let's go through fallbacks then
  510. BABYLON.Tools.Error("Unable to compile effect:");
  511. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  512. return " " + uniform;
  513. }));
  514. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  515. return " " + attribute;
  516. }));
  517. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  518. BABYLON.Tools.Error("Error: " + this._compilationError);
  519. if (previousProgram) {
  520. this._program = previousProgram;
  521. this._isReady = true;
  522. if (this.onError) {
  523. this.onError(this, this._compilationError);
  524. }
  525. this.onErrorObservable.notifyObservers(this);
  526. }
  527. if (fallbacks && fallbacks.isMoreFallbacks) {
  528. BABYLON.Tools.Error("Trying next fallback.");
  529. this.defines = fallbacks.reduce(this.defines);
  530. this._prepareEffect();
  531. }
  532. else {
  533. if (this.onError) {
  534. this.onError(this, this._compilationError);
  535. }
  536. this.onErrorObservable.notifyObservers(this);
  537. this.onErrorObservable.clear();
  538. // Unbind mesh reference in fallbacks
  539. if (this._fallbacks) {
  540. this._fallbacks.unBindMesh();
  541. }
  542. }
  543. }
  544. };
  545. Object.defineProperty(Effect.prototype, "isSupported", {
  546. get: function () {
  547. return this._compilationError === "";
  548. },
  549. enumerable: true,
  550. configurable: true
  551. });
  552. Effect.prototype._bindTexture = function (channel, texture) {
  553. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  554. };
  555. Effect.prototype.setTexture = function (channel, texture) {
  556. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  557. };
  558. Effect.prototype.setTextureArray = function (channel, textures) {
  559. if (this._samplers.indexOf(channel + "Ex") === -1) {
  560. var initialPos = this._samplers.indexOf(channel);
  561. for (var index = 1; index < textures.length; index++) {
  562. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  563. }
  564. }
  565. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  566. };
  567. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  568. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  569. };
  570. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  571. var cache = this._valueCache[uniformName];
  572. var flag = matrix.updateFlag;
  573. if (cache !== undefined && cache === flag) {
  574. return false;
  575. }
  576. this._valueCache[uniformName] = flag;
  577. return true;
  578. };
  579. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  580. var cache = this._valueCache[uniformName];
  581. if (!cache) {
  582. cache = [x, y];
  583. this._valueCache[uniformName] = cache;
  584. return true;
  585. }
  586. var changed = false;
  587. if (cache[0] !== x) {
  588. cache[0] = x;
  589. changed = true;
  590. }
  591. if (cache[1] !== y) {
  592. cache[1] = y;
  593. changed = true;
  594. }
  595. return changed;
  596. };
  597. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  598. var cache = this._valueCache[uniformName];
  599. if (!cache) {
  600. cache = [x, y, z];
  601. this._valueCache[uniformName] = cache;
  602. return true;
  603. }
  604. var changed = false;
  605. if (cache[0] !== x) {
  606. cache[0] = x;
  607. changed = true;
  608. }
  609. if (cache[1] !== y) {
  610. cache[1] = y;
  611. changed = true;
  612. }
  613. if (cache[2] !== z) {
  614. cache[2] = z;
  615. changed = true;
  616. }
  617. return changed;
  618. };
  619. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  620. var cache = this._valueCache[uniformName];
  621. if (!cache) {
  622. cache = [x, y, z, w];
  623. this._valueCache[uniformName] = cache;
  624. return true;
  625. }
  626. var changed = false;
  627. if (cache[0] !== x) {
  628. cache[0] = x;
  629. changed = true;
  630. }
  631. if (cache[1] !== y) {
  632. cache[1] = y;
  633. changed = true;
  634. }
  635. if (cache[2] !== z) {
  636. cache[2] = z;
  637. changed = true;
  638. }
  639. if (cache[3] !== w) {
  640. cache[3] = w;
  641. changed = true;
  642. }
  643. return changed;
  644. };
  645. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  646. var bufferName = this._uniformBuffersNames[name];
  647. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  648. return;
  649. }
  650. Effect._baseCache[bufferName] = buffer;
  651. this._engine.bindUniformBufferBase(buffer, bufferName);
  652. };
  653. Effect.prototype.bindUniformBlock = function (blockName, index) {
  654. this._engine.bindUniformBlock(this._program, blockName, index);
  655. };
  656. Effect.prototype.setInt = function (uniformName, value) {
  657. var cache = this._valueCache[uniformName];
  658. if (cache !== undefined && cache === value)
  659. return this;
  660. this._valueCache[uniformName] = value;
  661. this._engine.setInt(this.getUniform(uniformName), value);
  662. return this;
  663. };
  664. Effect.prototype.setIntArray = function (uniformName, array) {
  665. this._valueCache[uniformName] = null;
  666. this._engine.setIntArray(this.getUniform(uniformName), array);
  667. return this;
  668. };
  669. Effect.prototype.setIntArray2 = function (uniformName, array) {
  670. this._valueCache[uniformName] = null;
  671. this._engine.setIntArray2(this.getUniform(uniformName), array);
  672. return this;
  673. };
  674. Effect.prototype.setIntArray3 = function (uniformName, array) {
  675. this._valueCache[uniformName] = null;
  676. this._engine.setIntArray3(this.getUniform(uniformName), array);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray4 = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray4(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setFloatArray = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setFloatArray(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setArray = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setArray(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setArray2 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setArray2(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setArray3 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setArray3(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray4 = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray4(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setMatrices = function (uniformName, matrices) {
  725. if (!matrices) {
  726. return this;
  727. }
  728. this._valueCache[uniformName] = null;
  729. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  730. return this;
  731. };
  732. Effect.prototype.setMatrix = function (uniformName, matrix) {
  733. if (this._cacheMatrix(uniformName, matrix)) {
  734. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  735. }
  736. return this;
  737. };
  738. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  739. this._valueCache[uniformName] = null;
  740. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  741. return this;
  742. };
  743. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  744. this._valueCache[uniformName] = null;
  745. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  746. return this;
  747. };
  748. Effect.prototype.setFloat = function (uniformName, value) {
  749. var cache = this._valueCache[uniformName];
  750. if (cache !== undefined && cache === value)
  751. return this;
  752. this._valueCache[uniformName] = value;
  753. this._engine.setFloat(this.getUniform(uniformName), value);
  754. return this;
  755. };
  756. Effect.prototype.setBool = function (uniformName, bool) {
  757. var cache = this._valueCache[uniformName];
  758. if (cache !== undefined && cache === bool)
  759. return this;
  760. this._valueCache[uniformName] = bool;
  761. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  762. return this;
  763. };
  764. Effect.prototype.setVector2 = function (uniformName, vector2) {
  765. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  766. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  767. }
  768. return this;
  769. };
  770. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  771. if (this._cacheFloat2(uniformName, x, y)) {
  772. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  773. }
  774. return this;
  775. };
  776. Effect.prototype.setVector3 = function (uniformName, vector3) {
  777. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  778. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  783. if (this._cacheFloat3(uniformName, x, y, z)) {
  784. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector4 = function (uniformName, vector4) {
  789. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  790. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  795. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  796. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setColor3 = function (uniformName, color3) {
  801. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  802. this._engine.setColor3(this.getUniform(uniformName), color3);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  807. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  808. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  809. }
  810. return this;
  811. };
  812. Effect.ResetCache = function () {
  813. Effect._baseCache = {};
  814. };
  815. Effect._uniqueIdSeed = 0;
  816. Effect._baseCache = {};
  817. // Statics
  818. Effect.ShadersStore = {};
  819. Effect.IncludesShadersStore = {};
  820. return Effect;
  821. }());
  822. BABYLON.Effect = Effect;
  823. })(BABYLON || (BABYLON = {}));
  824. //# sourceMappingURL=babylon.effect.js.map
  825. //# sourceMappingURL=babylon.types.js.map
  826. var BABYLON;
  827. (function (BABYLON) {
  828. var KeyboardEventTypes = /** @class */ (function () {
  829. function KeyboardEventTypes() {
  830. }
  831. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  832. get: function () {
  833. return KeyboardEventTypes._KEYDOWN;
  834. },
  835. enumerable: true,
  836. configurable: true
  837. });
  838. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  839. get: function () {
  840. return KeyboardEventTypes._KEYUP;
  841. },
  842. enumerable: true,
  843. configurable: true
  844. });
  845. KeyboardEventTypes._KEYDOWN = 0x01;
  846. KeyboardEventTypes._KEYUP = 0x02;
  847. return KeyboardEventTypes;
  848. }());
  849. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  850. var KeyboardInfo = /** @class */ (function () {
  851. function KeyboardInfo(type, event) {
  852. this.type = type;
  853. this.event = event;
  854. }
  855. return KeyboardInfo;
  856. }());
  857. BABYLON.KeyboardInfo = KeyboardInfo;
  858. /**
  859. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  860. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  861. */
  862. var KeyboardInfoPre = /** @class */ (function (_super) {
  863. __extends(KeyboardInfoPre, _super);
  864. function KeyboardInfoPre(type, event) {
  865. var _this = _super.call(this, type, event) || this;
  866. _this.skipOnPointerObservable = false;
  867. return _this;
  868. }
  869. return KeyboardInfoPre;
  870. }(KeyboardInfo));
  871. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.keyboardEvents.js.map
  874. var BABYLON;
  875. (function (BABYLON) {
  876. var PointerEventTypes = /** @class */ (function () {
  877. function PointerEventTypes() {
  878. }
  879. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  880. get: function () {
  881. return PointerEventTypes._POINTERDOWN;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  887. get: function () {
  888. return PointerEventTypes._POINTERUP;
  889. },
  890. enumerable: true,
  891. configurable: true
  892. });
  893. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  894. get: function () {
  895. return PointerEventTypes._POINTERMOVE;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  901. get: function () {
  902. return PointerEventTypes._POINTERWHEEL;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  908. get: function () {
  909. return PointerEventTypes._POINTERPICK;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  915. get: function () {
  916. return PointerEventTypes._POINTERTAP;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  922. get: function () {
  923. return PointerEventTypes._POINTERDOUBLETAP;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. PointerEventTypes._POINTERDOWN = 0x01;
  929. PointerEventTypes._POINTERUP = 0x02;
  930. PointerEventTypes._POINTERMOVE = 0x04;
  931. PointerEventTypes._POINTERWHEEL = 0x08;
  932. PointerEventTypes._POINTERPICK = 0x10;
  933. PointerEventTypes._POINTERTAP = 0x20;
  934. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  935. return PointerEventTypes;
  936. }());
  937. BABYLON.PointerEventTypes = PointerEventTypes;
  938. var PointerInfoBase = /** @class */ (function () {
  939. function PointerInfoBase(type, event) {
  940. this.type = type;
  941. this.event = event;
  942. }
  943. return PointerInfoBase;
  944. }());
  945. BABYLON.PointerInfoBase = PointerInfoBase;
  946. /**
  947. * This class is used to store pointer related info for the onPrePointerObservable event.
  948. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  949. */
  950. var PointerInfoPre = /** @class */ (function (_super) {
  951. __extends(PointerInfoPre, _super);
  952. function PointerInfoPre(type, event, localX, localY) {
  953. var _this = _super.call(this, type, event) || this;
  954. _this.skipOnPointerObservable = false;
  955. _this.localPosition = new BABYLON.Vector2(localX, localY);
  956. return _this;
  957. }
  958. return PointerInfoPre;
  959. }(PointerInfoBase));
  960. BABYLON.PointerInfoPre = PointerInfoPre;
  961. /**
  962. * This type contains all the data related to a pointer event in Babylon.js.
  963. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  964. */
  965. var PointerInfo = /** @class */ (function (_super) {
  966. __extends(PointerInfo, _super);
  967. function PointerInfo(type, event, pickInfo) {
  968. var _this = _super.call(this, type, event) || this;
  969. _this.pickInfo = pickInfo;
  970. return _this;
  971. }
  972. return PointerInfo;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfo = PointerInfo;
  975. })(BABYLON || (BABYLON = {}));
  976. //# sourceMappingURL=babylon.pointerEvents.js.map
  977. var BABYLON;
  978. (function (BABYLON) {
  979. BABYLON.ToGammaSpace = 1 / 2.2;
  980. BABYLON.ToLinearSpace = 2.2;
  981. BABYLON.Epsilon = 0.001;
  982. /**
  983. * Class used to hold a RBG color
  984. */
  985. var Color3 = /** @class */ (function () {
  986. /**
  987. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  988. * @param r defines the red component (between 0 and 1, default is 0)
  989. * @param g defines the green component (between 0 and 1, default is 0)
  990. * @param b defines the blue component (between 0 and 1, default is 0)
  991. */
  992. function Color3(
  993. /**
  994. * Defines the red component (between 0 and 1, default is 0)
  995. */
  996. r,
  997. /**
  998. * Defines the green component (between 0 and 1, default is 0)
  999. */
  1000. g,
  1001. /**
  1002. * Defines the blue component (between 0 and 1, default is 0)
  1003. */
  1004. b) {
  1005. if (r === void 0) { r = 0; }
  1006. if (g === void 0) { g = 0; }
  1007. if (b === void 0) { b = 0; }
  1008. this.r = r;
  1009. this.g = g;
  1010. this.b = b;
  1011. }
  1012. /**
  1013. * Creates a string with the Color3 current values
  1014. * @returns the string representation of the Color3 object
  1015. */
  1016. Color3.prototype.toString = function () {
  1017. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Color3"
  1021. * @returns "Color3"
  1022. */
  1023. Color3.prototype.getClassName = function () {
  1024. return "Color3";
  1025. };
  1026. /**
  1027. * Compute the Color3 hash code
  1028. * @returns an unique number that can be used to hash Color3 objects
  1029. */
  1030. Color3.prototype.getHashCode = function () {
  1031. var hash = this.r || 0;
  1032. hash = (hash * 397) ^ (this.g || 0);
  1033. hash = (hash * 397) ^ (this.b || 0);
  1034. return hash;
  1035. };
  1036. // Operators
  1037. /**
  1038. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1039. * @param array defines the array where to store the r,g,b components
  1040. * @param index defines an optional index in the target array to define where to start storing values
  1041. * @returns the current Color3 object
  1042. */
  1043. Color3.prototype.toArray = function (array, index) {
  1044. if (index === undefined) {
  1045. index = 0;
  1046. }
  1047. array[index] = this.r;
  1048. array[index + 1] = this.g;
  1049. array[index + 2] = this.b;
  1050. return this;
  1051. };
  1052. /**
  1053. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1054. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1055. * @returns a new {BABYLON.Color4} object
  1056. */
  1057. Color3.prototype.toColor4 = function (alpha) {
  1058. if (alpha === void 0) { alpha = 1; }
  1059. return new Color4(this.r, this.g, this.b, alpha);
  1060. };
  1061. /**
  1062. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1063. * @returns the new array
  1064. */
  1065. Color3.prototype.asArray = function () {
  1066. var result = new Array();
  1067. this.toArray(result, 0);
  1068. return result;
  1069. };
  1070. /**
  1071. * Returns the luminance value
  1072. * @returns a float value
  1073. */
  1074. Color3.prototype.toLuminance = function () {
  1075. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1076. };
  1077. /**
  1078. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1079. * @param otherColor defines the second operand
  1080. * @returns the new Color3 object
  1081. */
  1082. Color3.prototype.multiply = function (otherColor) {
  1083. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1084. };
  1085. /**
  1086. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1087. * @param otherColor defines the second operand
  1088. * @param result defines the Color3 object where to store the result
  1089. * @returns the current Color3
  1090. */
  1091. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1092. result.r = this.r * otherColor.r;
  1093. result.g = this.g * otherColor.g;
  1094. result.b = this.b * otherColor.b;
  1095. return this;
  1096. };
  1097. /**
  1098. * Determines equality between Color3 objects
  1099. * @param otherColor defines the second operand
  1100. * @returns true if the rgb values are equal to the passed ones
  1101. */
  1102. Color3.prototype.equals = function (otherColor) {
  1103. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1104. };
  1105. /**
  1106. * Determines equality between the current Color3 object and a set of r,b,g values
  1107. * @param r defines the red component to check
  1108. * @param g defines the green component to check
  1109. * @param b defines the blue component to check
  1110. * @returns true if the rgb values are equal to the passed ones
  1111. */
  1112. Color3.prototype.equalsFloats = function (r, g, b) {
  1113. return this.r === r && this.g === g && this.b === b;
  1114. };
  1115. /**
  1116. * Multiplies in place each rgb value by scale
  1117. * @param scale defines the scaling factor
  1118. * @returns the updated Color3.
  1119. */
  1120. Color3.prototype.scale = function (scale) {
  1121. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1122. };
  1123. /**
  1124. * Multiplies the rgb values by scale and stores the result into "result"
  1125. * @param scale defines the scaling factor
  1126. * @param result defines the Color3 object where to store the result
  1127. * @returns the unmodified current Color3.
  1128. */
  1129. Color3.prototype.scaleToRef = function (scale, result) {
  1130. result.r = this.r * scale;
  1131. result.g = this.g * scale;
  1132. result.b = this.b * scale;
  1133. return this;
  1134. };
  1135. /**
  1136. * Clamps the rgb values by the min and max values and stores the result into "result"
  1137. * @param min defines minimum clamping value (default is 0)
  1138. * @param max defines maximum clamping value (default is 1)
  1139. * @param result defines color to store the result into
  1140. * @returns the original Color3
  1141. */
  1142. Color3.prototype.clampToRef = function (min, max, result) {
  1143. if (min === void 0) { min = 0; }
  1144. if (max === void 0) { max = 1; }
  1145. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1146. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1147. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1148. return this;
  1149. };
  1150. /**
  1151. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1152. * @param otherColor defines the second operand
  1153. * @returns the new Color3
  1154. */
  1155. Color3.prototype.add = function (otherColor) {
  1156. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1157. };
  1158. /**
  1159. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1160. * @param otherColor defines the second operand
  1161. * @param result defines Color3 object to store the result into
  1162. * @returns the unmodified current Color3
  1163. */
  1164. Color3.prototype.addToRef = function (otherColor, result) {
  1165. result.r = this.r + otherColor.r;
  1166. result.g = this.g + otherColor.g;
  1167. result.b = this.b + otherColor.b;
  1168. return this;
  1169. };
  1170. /**
  1171. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1172. * @param otherColor defines the second operand
  1173. * @returns the new Color3
  1174. */
  1175. Color3.prototype.subtract = function (otherColor) {
  1176. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1177. };
  1178. /**
  1179. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1180. * @param otherColor defines the second operand
  1181. * @param result defines Color3 object to store the result into
  1182. * @returns the unmodified current Color3
  1183. */
  1184. Color3.prototype.subtractToRef = function (otherColor, result) {
  1185. result.r = this.r - otherColor.r;
  1186. result.g = this.g - otherColor.g;
  1187. result.b = this.b - otherColor.b;
  1188. return this;
  1189. };
  1190. /**
  1191. * Copy the current object
  1192. * @returns a new Color3 copied the current one
  1193. */
  1194. Color3.prototype.clone = function () {
  1195. return new Color3(this.r, this.g, this.b);
  1196. };
  1197. /**
  1198. * Copies the rgb values from the source in the current Color3
  1199. * @param source defines the source Color3 object
  1200. * @returns the updated Color3 object
  1201. */
  1202. Color3.prototype.copyFrom = function (source) {
  1203. this.r = source.r;
  1204. this.g = source.g;
  1205. this.b = source.b;
  1206. return this;
  1207. };
  1208. /**
  1209. * Updates the Color3 rgb values from the passed floats
  1210. * @param r defines the red component to read from
  1211. * @param g defines the green component to read from
  1212. * @param b defines the blue component to read from
  1213. * @returns the current Color3 object
  1214. */
  1215. Color3.prototype.copyFromFloats = function (r, g, b) {
  1216. this.r = r;
  1217. this.g = g;
  1218. this.b = b;
  1219. return this;
  1220. };
  1221. /**
  1222. * Updates the Color3 rgb values from the passed floats
  1223. * @param r defines the red component to read from
  1224. * @param g defines the green component to read from
  1225. * @param b defines the blue component to read from
  1226. * @returns the current Color3 object
  1227. */
  1228. Color3.prototype.set = function (r, g, b) {
  1229. return this.copyFromFloats(r, g, b);
  1230. };
  1231. /**
  1232. * Compute the Color3 hexadecimal code as a string
  1233. * @returns a string containing the hexadecimal representation of the Color3 object
  1234. */
  1235. Color3.prototype.toHexString = function () {
  1236. var intR = (this.r * 255) | 0;
  1237. var intG = (this.g * 255) | 0;
  1238. var intB = (this.b * 255) | 0;
  1239. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1240. };
  1241. /**
  1242. * Computes a new Color3 converted from the current one to linear space
  1243. * @returns a new Color3 object
  1244. */
  1245. Color3.prototype.toLinearSpace = function () {
  1246. var convertedColor = new Color3();
  1247. this.toLinearSpaceToRef(convertedColor);
  1248. return convertedColor;
  1249. };
  1250. /**
  1251. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1252. * @param convertedColor defines the Color3 object where to store the linear space version
  1253. * @returns the unmodified Color3
  1254. */
  1255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1259. return this;
  1260. };
  1261. /**
  1262. * Computes a new Color3 converted from the current one to gamma space
  1263. * @returns a new Color3 object
  1264. */
  1265. Color3.prototype.toGammaSpace = function () {
  1266. var convertedColor = new Color3();
  1267. this.toGammaSpaceToRef(convertedColor);
  1268. return convertedColor;
  1269. };
  1270. /**
  1271. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1272. * @param convertedColor defines the Color3 object where to store the gamma space version
  1273. * @returns the unmodified Color3
  1274. */
  1275. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1276. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1277. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1278. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1279. return this;
  1280. };
  1281. // Statics
  1282. /**
  1283. * Creates a new Color3 from the string containing valid hexadecimal values
  1284. * @param hex defines a string containing valid hexadecimal values
  1285. * @returns a new Color3 object
  1286. */
  1287. Color3.FromHexString = function (hex) {
  1288. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1289. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1290. return new Color3(0, 0, 0);
  1291. }
  1292. var r = parseInt(hex.substring(1, 3), 16);
  1293. var g = parseInt(hex.substring(3, 5), 16);
  1294. var b = parseInt(hex.substring(5, 7), 16);
  1295. return Color3.FromInts(r, g, b);
  1296. };
  1297. /**
  1298. * Creates a new Vector3 from the starting index of the passed array
  1299. * @param array defines the source array
  1300. * @param offset defines an offset in the source array
  1301. * @returns a new Color3 object
  1302. */
  1303. Color3.FromArray = function (array, offset) {
  1304. if (offset === void 0) { offset = 0; }
  1305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1306. };
  1307. /**
  1308. * Creates a new Color3 from integer values (< 256)
  1309. * @param r defines the red component to read from (value between 0 and 255)
  1310. * @param g defines the green component to read from (value between 0 and 255)
  1311. * @param b defines the blue component to read from (value between 0 and 255)
  1312. * @returns a new Color3 object
  1313. */
  1314. Color3.FromInts = function (r, g, b) {
  1315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1316. };
  1317. /**
  1318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1319. * @param start defines the start Color3 value
  1320. * @param end defines the end Color3 value
  1321. * @param amount defines the gradient value between start and end
  1322. * @returns a new Color3 object
  1323. */
  1324. Color3.Lerp = function (start, end, amount) {
  1325. var r = start.r + ((end.r - start.r) * amount);
  1326. var g = start.g + ((end.g - start.g) * amount);
  1327. var b = start.b + ((end.b - start.b) * amount);
  1328. return new Color3(r, g, b);
  1329. };
  1330. /**
  1331. * Returns a Color3 value containing a red color
  1332. * @returns a new Color3 object
  1333. */
  1334. Color3.Red = function () { return new Color3(1, 0, 0); };
  1335. /**
  1336. * Returns a Color3 value containing a green color
  1337. * @returns a new Color3 object
  1338. */
  1339. Color3.Green = function () { return new Color3(0, 1, 0); };
  1340. /**
  1341. * Returns a Color3 value containing a blue color
  1342. * @returns a new Color3 object
  1343. */
  1344. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1345. /**
  1346. * Returns a Color3 value containing a black color
  1347. * @returns a new Color3 object
  1348. */
  1349. Color3.Black = function () { return new Color3(0, 0, 0); };
  1350. /**
  1351. * Returns a Color3 value containing a white color
  1352. * @returns a new Color3 object
  1353. */
  1354. Color3.White = function () { return new Color3(1, 1, 1); };
  1355. /**
  1356. * Returns a Color3 value containing a purple color
  1357. * @returns a new Color3 object
  1358. */
  1359. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1360. /**
  1361. * Returns a Color3 value containing a magenta color
  1362. * @returns a new Color3 object
  1363. */
  1364. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1365. /**
  1366. * Returns a Color3 value containing a yellow color
  1367. * @returns a new Color3 object
  1368. */
  1369. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1370. /**
  1371. * Returns a Color3 value containing a gray color
  1372. * @returns a new Color3 object
  1373. */
  1374. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1375. /**
  1376. * Returns a Color3 value containing a teal color
  1377. * @returns a new Color3 object
  1378. */
  1379. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1380. /**
  1381. * Returns a Color3 value containing a random color
  1382. * @returns a new Color3 object
  1383. */
  1384. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1385. return Color3;
  1386. }());
  1387. BABYLON.Color3 = Color3;
  1388. /**
  1389. * Class used to hold a RBGA color
  1390. */
  1391. var Color4 = /** @class */ (function () {
  1392. /**
  1393. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1394. * @param r defines the red component (between 0 and 1, default is 0)
  1395. * @param g defines the green component (between 0 and 1, default is 0)
  1396. * @param b defines the blue component (between 0 and 1, default is 0)
  1397. * @param a defines the alpha component (between 0 and 1, default is 1)
  1398. */
  1399. function Color4(
  1400. /**
  1401. * Defines the red component (between 0 and 1, default is 0)
  1402. */
  1403. r,
  1404. /**
  1405. * Defines the green component (between 0 and 1, default is 0)
  1406. */
  1407. g,
  1408. /**
  1409. * Defines the blue component (between 0 and 1, default is 0)
  1410. */
  1411. b,
  1412. /**
  1413. * Defines the alpha component (between 0 and 1, default is 1)
  1414. */
  1415. a) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. if (a === void 0) { a = 1; }
  1420. this.r = r;
  1421. this.g = g;
  1422. this.b = b;
  1423. this.a = a;
  1424. }
  1425. // Operators
  1426. /**
  1427. * Adds in place the passed Color4 values to the current Color4 object
  1428. * @param right defines the second operand
  1429. * @returns the current updated Color4 object
  1430. */
  1431. Color4.prototype.addInPlace = function (right) {
  1432. this.r += right.r;
  1433. this.g += right.g;
  1434. this.b += right.b;
  1435. this.a += right.a;
  1436. return this;
  1437. };
  1438. /**
  1439. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1440. * @returns the new array
  1441. */
  1442. Color4.prototype.asArray = function () {
  1443. var result = new Array();
  1444. this.toArray(result, 0);
  1445. return result;
  1446. };
  1447. /**
  1448. * Stores from the starting index in the passed array the Color4 successive values
  1449. * @param array defines the array where to store the r,g,b components
  1450. * @param index defines an optional index in the target array to define where to start storing values
  1451. * @returns the current Color4 object
  1452. */
  1453. Color4.prototype.toArray = function (array, index) {
  1454. if (index === undefined) {
  1455. index = 0;
  1456. }
  1457. array[index] = this.r;
  1458. array[index + 1] = this.g;
  1459. array[index + 2] = this.b;
  1460. array[index + 3] = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1465. * @param right defines the second operand
  1466. * @returns a new Color4 object
  1467. */
  1468. Color4.prototype.add = function (right) {
  1469. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1470. };
  1471. /**
  1472. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1473. * @param right defines the second operand
  1474. * @returns a new Color4 object
  1475. */
  1476. Color4.prototype.subtract = function (right) {
  1477. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1478. };
  1479. /**
  1480. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1481. * @param right defines the second operand
  1482. * @param result defines the Color4 object where to store the result
  1483. * @returns the current Color4 object
  1484. */
  1485. Color4.prototype.subtractToRef = function (right, result) {
  1486. result.r = this.r - right.r;
  1487. result.g = this.g - right.g;
  1488. result.b = this.b - right.b;
  1489. result.a = this.a - right.a;
  1490. return this;
  1491. };
  1492. /**
  1493. * Creates a new Color4 with the current Color4 values multiplied by scale
  1494. * @param scale defines the scaling factor to apply
  1495. * @returns a new Color4 object
  1496. */
  1497. Color4.prototype.scale = function (scale) {
  1498. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1499. };
  1500. /**
  1501. * Multiplies the current Color4 values by scale and stores the result in "result"
  1502. * @param scale defines the scaling factor to apply
  1503. * @param result defines the Color4 object where to store the result
  1504. * @returns the current Color4.
  1505. */
  1506. Color4.prototype.scaleToRef = function (scale, result) {
  1507. result.r = this.r * scale;
  1508. result.g = this.g * scale;
  1509. result.b = this.b * scale;
  1510. result.a = this.a * scale;
  1511. return this;
  1512. };
  1513. /**
  1514. * Clamps the rgb values by the min and max values and stores the result into "result"
  1515. * @param min defines minimum clamping value (default is 0)
  1516. * @param max defines maximum clamping value (default is 1)
  1517. * @param result defines color to store the result into.
  1518. * @returns the cuurent Color4
  1519. */
  1520. Color4.prototype.clampToRef = function (min, max, result) {
  1521. if (min === void 0) { min = 0; }
  1522. if (max === void 0) { max = 1; }
  1523. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1524. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1525. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1526. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1527. return this;
  1528. };
  1529. /**
  1530. * Multipy an Color4 value by another and return a new Color4 object
  1531. * @param color defines the Color4 value to multiply by
  1532. * @returns a new Color4 object
  1533. */
  1534. Color4.prototype.multiply = function (color) {
  1535. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1536. };
  1537. /**
  1538. * Multipy a Color4 value by another and push the result in a reference value
  1539. * @param color defines the Color4 value to multiply by
  1540. * @param result defines the Color4 to fill the result in
  1541. * @returns the result Color4
  1542. */
  1543. Color4.prototype.multiplyToRef = function (color, result) {
  1544. result.r = this.r * color.r;
  1545. result.g = this.g * color.g;
  1546. result.b = this.b * color.b;
  1547. result.a = this.a * color.a;
  1548. return result;
  1549. };
  1550. /**
  1551. * Creates a string with the Color4 current values
  1552. * @returns the string representation of the Color4 object
  1553. */
  1554. Color4.prototype.toString = function () {
  1555. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1556. };
  1557. /**
  1558. * Returns the string "Color4"
  1559. * @returns "Color4"
  1560. */
  1561. Color4.prototype.getClassName = function () {
  1562. return "Color4";
  1563. };
  1564. /**
  1565. * Compute the Color4 hash code
  1566. * @returns an unique number that can be used to hash Color4 objects
  1567. */
  1568. Color4.prototype.getHashCode = function () {
  1569. var hash = this.r || 0;
  1570. hash = (hash * 397) ^ (this.g || 0);
  1571. hash = (hash * 397) ^ (this.b || 0);
  1572. hash = (hash * 397) ^ (this.a || 0);
  1573. return hash;
  1574. };
  1575. /**
  1576. * Creates a new Color4 copied from the current one
  1577. * @returns a new Color4 object
  1578. */
  1579. Color4.prototype.clone = function () {
  1580. return new Color4(this.r, this.g, this.b, this.a);
  1581. };
  1582. /**
  1583. * Copies the passed Color4 values into the current one
  1584. * @param source defines the source Color4 object
  1585. * @returns the current updated Color4 object
  1586. */
  1587. Color4.prototype.copyFrom = function (source) {
  1588. this.r = source.r;
  1589. this.g = source.g;
  1590. this.b = source.b;
  1591. this.a = source.a;
  1592. return this;
  1593. };
  1594. /**
  1595. * Copies the passed float values into the current one
  1596. * @param r defines the red component to read from
  1597. * @param g defines the green component to read from
  1598. * @param b defines the blue component to read from
  1599. * @param a defines the alpha component to read from
  1600. * @returns the current updated Color4 object
  1601. */
  1602. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1603. this.r = r;
  1604. this.g = g;
  1605. this.b = b;
  1606. this.a = a;
  1607. return this;
  1608. };
  1609. /**
  1610. * Copies the passed float values into the current one
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @param a defines the alpha component to read from
  1615. * @returns the current updated Color4 object
  1616. */
  1617. Color4.prototype.set = function (r, g, b, a) {
  1618. return this.copyFromFloats(r, g, b, a);
  1619. };
  1620. /**
  1621. * Compute the Color4 hexadecimal code as a string
  1622. * @returns a string containing the hexadecimal representation of the Color4 object
  1623. */
  1624. Color4.prototype.toHexString = function () {
  1625. var intR = (this.r * 255) | 0;
  1626. var intG = (this.g * 255) | 0;
  1627. var intB = (this.b * 255) | 0;
  1628. var intA = (this.a * 255) | 0;
  1629. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1630. };
  1631. /**
  1632. * Computes a new Color4 converted from the current one to linear space
  1633. * @returns a new Color4 object
  1634. */
  1635. Color4.prototype.toLinearSpace = function () {
  1636. var convertedColor = new Color4();
  1637. this.toLinearSpaceToRef(convertedColor);
  1638. return convertedColor;
  1639. };
  1640. /**
  1641. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1642. * @param convertedColor defines the Color4 object where to store the linear space version
  1643. * @returns the unmodified Color4
  1644. */
  1645. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1646. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1647. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1648. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1649. convertedColor.a = this.a;
  1650. return this;
  1651. };
  1652. /**
  1653. * Computes a new Color4 converted from the current one to gamma space
  1654. * @returns a new Color4 object
  1655. */
  1656. Color4.prototype.toGammaSpace = function () {
  1657. var convertedColor = new Color4();
  1658. this.toGammaSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color4 object where to store the gamma space version
  1664. * @returns the unmodified Color4
  1665. */
  1666. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1670. convertedColor.a = this.a;
  1671. return this;
  1672. };
  1673. // Statics
  1674. /**
  1675. * Creates a new Color4 from the string containing valid hexadecimal values
  1676. * @param hex defines a string containing valid hexadecimal values
  1677. * @returns a new Color4 object
  1678. */
  1679. Color4.FromHexString = function (hex) {
  1680. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1681. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1682. return new Color4(0.0, 0.0, 0.0, 0.0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. var a = parseInt(hex.substring(7, 9), 16);
  1688. return Color4.FromInts(r, g, b, a);
  1689. };
  1690. /**
  1691. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1692. * @param left defines the start value
  1693. * @param right defines the end value
  1694. * @param amount defines the gradient factor
  1695. * @returns a new Color4 object
  1696. */
  1697. Color4.Lerp = function (left, right, amount) {
  1698. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1699. Color4.LerpToRef(left, right, amount, result);
  1700. return result;
  1701. };
  1702. /**
  1703. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1704. * @param left defines the start value
  1705. * @param right defines the end value
  1706. * @param amount defines the gradient factor
  1707. * @param result defines the Color4 object where to store data
  1708. */
  1709. Color4.LerpToRef = function (left, right, amount, result) {
  1710. result.r = left.r + (right.r - left.r) * amount;
  1711. result.g = left.g + (right.g - left.g) * amount;
  1712. result.b = left.b + (right.b - left.b) * amount;
  1713. result.a = left.a + (right.a - left.a) * amount;
  1714. };
  1715. /**
  1716. * Creates a new Color4 from the starting index element of the passed array
  1717. * @param array defines the source array to read from
  1718. * @param offset defines the offset in the source array
  1719. * @returns a new Color4 object
  1720. */
  1721. Color4.FromArray = function (array, offset) {
  1722. if (offset === void 0) { offset = 0; }
  1723. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1724. };
  1725. /**
  1726. * Creates a new Color3 from integer values (< 256)
  1727. * @param r defines the red component to read from (value between 0 and 255)
  1728. * @param g defines the green component to read from (value between 0 and 255)
  1729. * @param b defines the blue component to read from (value between 0 and 255)
  1730. * @param a defines the alpha component to read from (value between 0 and 255)
  1731. * @returns a new Color3 object
  1732. */
  1733. Color4.FromInts = function (r, g, b, a) {
  1734. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1735. };
  1736. /**
  1737. * Check the content of a given array and convert it to an array containing RGBA data
  1738. * If the original array was already containing count * 4 values then it is returned directly
  1739. * @param colors defines the array to check
  1740. * @param count defines the number of RGBA data to expect
  1741. * @returns an array containing count * 4 values (RGBA)
  1742. */
  1743. Color4.CheckColors4 = function (colors, count) {
  1744. // Check if color3 was used
  1745. if (colors.length === count * 3) {
  1746. var colors4 = [];
  1747. for (var index = 0; index < colors.length; index += 3) {
  1748. var newIndex = (index / 3) * 4;
  1749. colors4[newIndex] = colors[index];
  1750. colors4[newIndex + 1] = colors[index + 1];
  1751. colors4[newIndex + 2] = colors[index + 2];
  1752. colors4[newIndex + 3] = 1.0;
  1753. }
  1754. return colors4;
  1755. }
  1756. return colors;
  1757. };
  1758. return Color4;
  1759. }());
  1760. BABYLON.Color4 = Color4;
  1761. var Vector2 = /** @class */ (function () {
  1762. /**
  1763. * Creates a new Vector2 from the passed x and y coordinates.
  1764. */
  1765. function Vector2(x, y) {
  1766. this.x = x;
  1767. this.y = y;
  1768. }
  1769. /**
  1770. * Returns a string with the Vector2 coordinates.
  1771. */
  1772. Vector2.prototype.toString = function () {
  1773. return "{X: " + this.x + " Y:" + this.y + "}";
  1774. };
  1775. /**
  1776. * Returns the string "Vector2"
  1777. */
  1778. Vector2.prototype.getClassName = function () {
  1779. return "Vector2";
  1780. };
  1781. /**
  1782. * Returns the Vector2 hash code as a number.
  1783. */
  1784. Vector2.prototype.getHashCode = function () {
  1785. var hash = this.x || 0;
  1786. hash = (hash * 397) ^ (this.y || 0);
  1787. return hash;
  1788. };
  1789. // Operators
  1790. /**
  1791. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1792. * Returns the Vector2.
  1793. */
  1794. Vector2.prototype.toArray = function (array, index) {
  1795. if (index === void 0) { index = 0; }
  1796. array[index] = this.x;
  1797. array[index + 1] = this.y;
  1798. return this;
  1799. };
  1800. /**
  1801. * Returns a new array with 2 elements : the Vector2 coordinates.
  1802. */
  1803. Vector2.prototype.asArray = function () {
  1804. var result = new Array();
  1805. this.toArray(result, 0);
  1806. return result;
  1807. };
  1808. /**
  1809. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1810. * Returns the updated Vector2.
  1811. */
  1812. Vector2.prototype.copyFrom = function (source) {
  1813. this.x = source.x;
  1814. this.y = source.y;
  1815. return this;
  1816. };
  1817. /**
  1818. * Sets the Vector2 coordinates with the passed floats.
  1819. * Returns the updated Vector2.
  1820. */
  1821. Vector2.prototype.copyFromFloats = function (x, y) {
  1822. this.x = x;
  1823. this.y = y;
  1824. return this;
  1825. };
  1826. /**
  1827. * Sets the Vector2 coordinates with the passed floats.
  1828. * Returns the updated Vector2.
  1829. */
  1830. Vector2.prototype.set = function (x, y) {
  1831. return this.copyFromFloats(x, y);
  1832. };
  1833. /**
  1834. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1835. */
  1836. Vector2.prototype.add = function (otherVector) {
  1837. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1838. };
  1839. /**
  1840. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1841. * Returns the Vector2.
  1842. */
  1843. Vector2.prototype.addToRef = function (otherVector, result) {
  1844. result.x = this.x + otherVector.x;
  1845. result.y = this.y + otherVector.y;
  1846. return this;
  1847. };
  1848. /**
  1849. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1850. * Returns the updated Vector2.
  1851. */
  1852. Vector2.prototype.addInPlace = function (otherVector) {
  1853. this.x += otherVector.x;
  1854. this.y += otherVector.y;
  1855. return this;
  1856. };
  1857. /**
  1858. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1859. */
  1860. Vector2.prototype.addVector3 = function (otherVector) {
  1861. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1862. };
  1863. /**
  1864. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1865. */
  1866. Vector2.prototype.subtract = function (otherVector) {
  1867. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1868. };
  1869. /**
  1870. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1871. * Returns the Vector2.
  1872. */
  1873. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1874. result.x = this.x - otherVector.x;
  1875. result.y = this.y - otherVector.y;
  1876. return this;
  1877. };
  1878. /**
  1879. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1880. * Returns the updated Vector2.
  1881. */
  1882. Vector2.prototype.subtractInPlace = function (otherVector) {
  1883. this.x -= otherVector.x;
  1884. this.y -= otherVector.y;
  1885. return this;
  1886. };
  1887. /**
  1888. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1889. * Returns the updated Vector2.
  1890. */
  1891. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1892. this.x *= otherVector.x;
  1893. this.y *= otherVector.y;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1898. */
  1899. Vector2.prototype.multiply = function (otherVector) {
  1900. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1901. };
  1902. /**
  1903. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1904. * Returns the Vector2.
  1905. */
  1906. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1907. result.x = this.x * otherVector.x;
  1908. result.y = this.y * otherVector.y;
  1909. return this;
  1910. };
  1911. /**
  1912. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1913. */
  1914. Vector2.prototype.multiplyByFloats = function (x, y) {
  1915. return new Vector2(this.x * x, this.y * y);
  1916. };
  1917. /**
  1918. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1919. */
  1920. Vector2.prototype.divide = function (otherVector) {
  1921. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1922. };
  1923. /**
  1924. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1925. * Returns the Vector2.
  1926. */
  1927. Vector2.prototype.divideToRef = function (otherVector, result) {
  1928. result.x = this.x / otherVector.x;
  1929. result.y = this.y / otherVector.y;
  1930. return this;
  1931. };
  1932. /**
  1933. * Divides the current Vector3 coordinates by the passed ones.
  1934. * Returns the updated Vector3.
  1935. */
  1936. Vector2.prototype.divideInPlace = function (otherVector) {
  1937. return this.divideToRef(otherVector, this);
  1938. };
  1939. /**
  1940. * Returns a new Vector2 with current Vector2 negated coordinates.
  1941. */
  1942. Vector2.prototype.negate = function () {
  1943. return new Vector2(-this.x, -this.y);
  1944. };
  1945. /**
  1946. * Multiply the Vector2 coordinates by scale.
  1947. * Returns the updated Vector2.
  1948. */
  1949. Vector2.prototype.scaleInPlace = function (scale) {
  1950. this.x *= scale;
  1951. this.y *= scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1956. */
  1957. Vector2.prototype.scale = function (scale) {
  1958. return new Vector2(this.x * scale, this.y * scale);
  1959. };
  1960. /**
  1961. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1962. */
  1963. Vector2.prototype.equals = function (otherVector) {
  1964. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1965. };
  1966. /**
  1967. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1968. */
  1969. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1970. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1971. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1972. };
  1973. // Properties
  1974. /**
  1975. * Returns the vector length (float).
  1976. */
  1977. Vector2.prototype.length = function () {
  1978. return Math.sqrt(this.x * this.x + this.y * this.y);
  1979. };
  1980. /**
  1981. * Returns the vector squared length (float);
  1982. */
  1983. Vector2.prototype.lengthSquared = function () {
  1984. return (this.x * this.x + this.y * this.y);
  1985. };
  1986. // Methods
  1987. /**
  1988. * Normalize the vector.
  1989. * Returns the updated Vector2.
  1990. */
  1991. Vector2.prototype.normalize = function () {
  1992. var len = this.length();
  1993. if (len === 0)
  1994. return this;
  1995. var num = 1.0 / len;
  1996. this.x *= num;
  1997. this.y *= num;
  1998. return this;
  1999. };
  2000. /**
  2001. * Returns a new Vector2 copied from the Vector2.
  2002. */
  2003. Vector2.prototype.clone = function () {
  2004. return new Vector2(this.x, this.y);
  2005. };
  2006. // Statics
  2007. /**
  2008. * Returns a new Vector2(0, 0)
  2009. */
  2010. Vector2.Zero = function () {
  2011. return new Vector2(0, 0);
  2012. };
  2013. /**
  2014. * Returns a new Vector2(1, 1)
  2015. */
  2016. Vector2.One = function () {
  2017. return new Vector2(1, 1);
  2018. };
  2019. /**
  2020. * Returns a new Vector2 set from the passed index element of the passed array.
  2021. */
  2022. Vector2.FromArray = function (array, offset) {
  2023. if (offset === void 0) { offset = 0; }
  2024. return new Vector2(array[offset], array[offset + 1]);
  2025. };
  2026. /**
  2027. * Sets "result" from the passed index element of the passed array.
  2028. */
  2029. Vector2.FromArrayToRef = function (array, offset, result) {
  2030. result.x = array[offset];
  2031. result.y = array[offset + 1];
  2032. };
  2033. /**
  2034. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2035. */
  2036. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2037. var squared = amount * amount;
  2038. var cubed = amount * squared;
  2039. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2040. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2041. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2042. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2043. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2044. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2045. return new Vector2(x, y);
  2046. };
  2047. /**
  2048. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2049. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2050. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2051. */
  2052. Vector2.Clamp = function (value, min, max) {
  2053. var x = value.x;
  2054. x = (x > max.x) ? max.x : x;
  2055. x = (x < min.x) ? min.x : x;
  2056. var y = value.y;
  2057. y = (y > max.y) ? max.y : y;
  2058. y = (y < min.y) ? min.y : y;
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2063. */
  2064. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2065. var squared = amount * amount;
  2066. var cubed = amount * squared;
  2067. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2068. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2069. var part3 = (cubed - (2.0 * squared)) + amount;
  2070. var part4 = cubed - squared;
  2071. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2072. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2077. */
  2078. Vector2.Lerp = function (start, end, amount) {
  2079. var x = start.x + ((end.x - start.x) * amount);
  2080. var y = start.y + ((end.y - start.y) * amount);
  2081. return new Vector2(x, y);
  2082. };
  2083. /**
  2084. * Returns the dot product (float) of the vector "left" and the vector "right".
  2085. */
  2086. Vector2.Dot = function (left, right) {
  2087. return left.x * right.x + left.y * right.y;
  2088. };
  2089. /**
  2090. * Returns a new Vector2 equal to the normalized passed vector.
  2091. */
  2092. Vector2.Normalize = function (vector) {
  2093. var newVector = vector.clone();
  2094. newVector.normalize();
  2095. return newVector;
  2096. };
  2097. /**
  2098. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2099. */
  2100. Vector2.Minimize = function (left, right) {
  2101. var x = (left.x < right.x) ? left.x : right.x;
  2102. var y = (left.y < right.y) ? left.y : right.y;
  2103. return new Vector2(x, y);
  2104. };
  2105. /**
  2106. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2107. */
  2108. Vector2.Maximize = function (left, right) {
  2109. var x = (left.x > right.x) ? left.x : right.x;
  2110. var y = (left.y > right.y) ? left.y : right.y;
  2111. return new Vector2(x, y);
  2112. };
  2113. /**
  2114. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2115. */
  2116. Vector2.Transform = function (vector, transformation) {
  2117. var r = Vector2.Zero();
  2118. Vector2.TransformToRef(vector, transformation, r);
  2119. return r;
  2120. };
  2121. /**
  2122. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2123. */
  2124. Vector2.TransformToRef = function (vector, transformation, result) {
  2125. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2126. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2127. result.x = x;
  2128. result.y = y;
  2129. };
  2130. /**
  2131. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2132. */
  2133. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2134. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2135. var sign = a < 0 ? -1 : 1;
  2136. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2137. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2138. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2139. };
  2140. /**
  2141. * Returns the distance (float) between the vectors "value1" and "value2".
  2142. */
  2143. Vector2.Distance = function (value1, value2) {
  2144. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2145. };
  2146. /**
  2147. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2148. */
  2149. Vector2.DistanceSquared = function (value1, value2) {
  2150. var x = value1.x - value2.x;
  2151. var y = value1.y - value2.y;
  2152. return (x * x) + (y * y);
  2153. };
  2154. /**
  2155. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Center = function (value1, value2) {
  2158. var center = value1.add(value2);
  2159. center.scaleInPlace(0.5);
  2160. return center;
  2161. };
  2162. /**
  2163. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2164. */
  2165. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2166. var l2 = Vector2.DistanceSquared(segA, segB);
  2167. if (l2 === 0.0) {
  2168. return Vector2.Distance(p, segA);
  2169. }
  2170. var v = segB.subtract(segA);
  2171. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2172. var proj = segA.add(v.multiplyByFloats(t, t));
  2173. return Vector2.Distance(p, proj);
  2174. };
  2175. return Vector2;
  2176. }());
  2177. BABYLON.Vector2 = Vector2;
  2178. var Vector3 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2181. * A Vector3 is the main object used in 3D geometry.
  2182. * It can represent etiher the coordinates of a point the space, either a direction.
  2183. */
  2184. function Vector3(x, y, z) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. }
  2189. /**
  2190. * Returns a string with the Vector3 coordinates.
  2191. */
  2192. Vector3.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2194. };
  2195. /**
  2196. * Returns the string "Vector3"
  2197. */
  2198. Vector3.prototype.getClassName = function () {
  2199. return "Vector3";
  2200. };
  2201. /**
  2202. * Returns the Vector hash code.
  2203. */
  2204. Vector3.prototype.getHashCode = function () {
  2205. var hash = this.x || 0;
  2206. hash = (hash * 397) ^ (this.y || 0);
  2207. hash = (hash * 397) ^ (this.z || 0);
  2208. return hash;
  2209. };
  2210. // Operators
  2211. /**
  2212. * Returns a new array with three elements : the coordinates the Vector3.
  2213. */
  2214. Vector3.prototype.asArray = function () {
  2215. var result = [];
  2216. this.toArray(result, 0);
  2217. return result;
  2218. };
  2219. /**
  2220. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2221. * Returns the Vector3.
  2222. */
  2223. Vector3.prototype.toArray = function (array, index) {
  2224. if (index === void 0) { index = 0; }
  2225. array[index] = this.x;
  2226. array[index + 1] = this.y;
  2227. array[index + 2] = this.z;
  2228. return this;
  2229. };
  2230. /**
  2231. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2232. */
  2233. Vector3.prototype.toQuaternion = function () {
  2234. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2235. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2236. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2237. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2238. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2239. var cosy = Math.cos(this.y * 0.5);
  2240. var siny = Math.sin(this.y * 0.5);
  2241. result.x = coszMinusx * siny;
  2242. result.y = -sinzMinusx * siny;
  2243. result.z = sinxPlusz * cosy;
  2244. result.w = cosxPlusz * cosy;
  2245. return result;
  2246. };
  2247. /**
  2248. * Adds the passed vector to the current Vector3.
  2249. * Returns the updated Vector3.
  2250. */
  2251. Vector3.prototype.addInPlace = function (otherVector) {
  2252. this.x += otherVector.x;
  2253. this.y += otherVector.y;
  2254. this.z += otherVector.z;
  2255. return this;
  2256. };
  2257. /**
  2258. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2259. */
  2260. Vector3.prototype.add = function (otherVector) {
  2261. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2262. };
  2263. /**
  2264. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2265. * Returns the current Vector3.
  2266. */
  2267. Vector3.prototype.addToRef = function (otherVector, result) {
  2268. result.x = this.x + otherVector.x;
  2269. result.y = this.y + otherVector.y;
  2270. result.z = this.z + otherVector.z;
  2271. return this;
  2272. };
  2273. /**
  2274. * Subtract the passed vector from the current Vector3.
  2275. * Returns the updated Vector3.
  2276. */
  2277. Vector3.prototype.subtractInPlace = function (otherVector) {
  2278. this.x -= otherVector.x;
  2279. this.y -= otherVector.y;
  2280. this.z -= otherVector.z;
  2281. return this;
  2282. };
  2283. /**
  2284. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2285. */
  2286. Vector3.prototype.subtract = function (otherVector) {
  2287. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2288. };
  2289. /**
  2290. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2291. * Returns the current Vector3.
  2292. */
  2293. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2294. result.x = this.x - otherVector.x;
  2295. result.y = this.y - otherVector.y;
  2296. result.z = this.z - otherVector.z;
  2297. return this;
  2298. };
  2299. /**
  2300. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2301. */
  2302. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2303. return new Vector3(this.x - x, this.y - y, this.z - z);
  2304. };
  2305. /**
  2306. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2307. * Returns the current Vector3.
  2308. */
  2309. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2310. result.x = this.x - x;
  2311. result.y = this.y - y;
  2312. result.z = this.z - z;
  2313. return this;
  2314. };
  2315. /**
  2316. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2317. */
  2318. Vector3.prototype.negate = function () {
  2319. return new Vector3(-this.x, -this.y, -this.z);
  2320. };
  2321. /**
  2322. * Multiplies the Vector3 coordinates by the float "scale".
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.scaleInPlace = function (scale) {
  2326. this.x *= scale;
  2327. this.y *= scale;
  2328. this.z *= scale;
  2329. return this;
  2330. };
  2331. /**
  2332. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2333. */
  2334. Vector3.prototype.scale = function (scale) {
  2335. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2336. };
  2337. /**
  2338. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2339. * Returns the current Vector3.
  2340. */
  2341. Vector3.prototype.scaleToRef = function (scale, result) {
  2342. result.x = this.x * scale;
  2343. result.y = this.y * scale;
  2344. result.z = this.z * scale;
  2345. return this;
  2346. };
  2347. /**
  2348. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2349. */
  2350. Vector3.prototype.equals = function (otherVector) {
  2351. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2352. };
  2353. /**
  2354. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2355. */
  2356. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2357. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2358. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2359. };
  2360. /**
  2361. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2362. */
  2363. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2364. return this.x === x && this.y === y && this.z === z;
  2365. };
  2366. /**
  2367. * Muliplies the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2371. this.x *= otherVector.x;
  2372. this.y *= otherVector.y;
  2373. this.z *= otherVector.z;
  2374. return this;
  2375. };
  2376. /**
  2377. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2378. */
  2379. Vector3.prototype.multiply = function (otherVector) {
  2380. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2381. };
  2382. /**
  2383. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2384. * Returns the current Vector3.
  2385. */
  2386. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. result.z = this.z * otherVector.z;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2394. */
  2395. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2396. return new Vector3(this.x * x, this.y * y, this.z * z);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2400. */
  2401. Vector3.prototype.divide = function (otherVector) {
  2402. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2403. };
  2404. /**
  2405. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2406. * Returns the current Vector3.
  2407. */
  2408. Vector3.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. result.z = this.z / otherVector.z;
  2412. return this;
  2413. };
  2414. /**
  2415. * Divides the current Vector3 coordinates by the passed ones.
  2416. * Returns the updated Vector3.
  2417. */
  2418. Vector3.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2423. * Returns the updated Vector3.
  2424. */
  2425. Vector3.prototype.MinimizeInPlace = function (other) {
  2426. if (other.x < this.x)
  2427. this.x = other.x;
  2428. if (other.y < this.y)
  2429. this.y = other.y;
  2430. if (other.z < this.z)
  2431. this.z = other.z;
  2432. return this;
  2433. };
  2434. /**
  2435. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2436. * Returns the updated Vector3.
  2437. */
  2438. Vector3.prototype.MaximizeInPlace = function (other) {
  2439. if (other.x > this.x)
  2440. this.x = other.x;
  2441. if (other.y > this.y)
  2442. this.y = other.y;
  2443. if (other.z > this.z)
  2444. this.z = other.z;
  2445. return this;
  2446. };
  2447. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2448. /**
  2449. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2450. */
  2451. get: function () {
  2452. var absX = Math.abs(this.x);
  2453. var absY = Math.abs(this.y);
  2454. if (absX !== absY) {
  2455. return true;
  2456. }
  2457. var absZ = Math.abs(this.z);
  2458. if (absX !== absZ) {
  2459. return true;
  2460. }
  2461. if (absY !== absZ) {
  2462. return true;
  2463. }
  2464. return false;
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. // Properties
  2470. /**
  2471. * Returns the length of the Vector3 (float).
  2472. */
  2473. Vector3.prototype.length = function () {
  2474. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2475. };
  2476. /**
  2477. * Returns the squared length of the Vector3 (float).
  2478. */
  2479. Vector3.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2481. };
  2482. /**
  2483. * Normalize the current Vector3.
  2484. * Returns the updated Vector3.
  2485. * /!\ In place operation.
  2486. */
  2487. Vector3.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0 || len === 1.0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. this.z *= num;
  2495. return this;
  2496. };
  2497. /**
  2498. * Normalize the current Vector3 to a new vector.
  2499. * @returns the new Vector3.
  2500. */
  2501. Vector3.prototype.normalizeToNew = function () {
  2502. var normalized = new Vector3(0, 0, 0);
  2503. this.normalizeToRef(normalized);
  2504. return normalized;
  2505. };
  2506. /**
  2507. * Normalize the current Vector3 to the reference.
  2508. * @param the reference to update.
  2509. * @returns the updated Vector3.
  2510. */
  2511. Vector3.prototype.normalizeToRef = function (reference) {
  2512. var len = this.length();
  2513. if (len === 0 || len === 1.0) {
  2514. reference.set(this.x, this.y, this.z);
  2515. return reference;
  2516. }
  2517. var scale = 1.0 / len;
  2518. this.scaleToRef(scale, reference);
  2519. return reference;
  2520. };
  2521. /**
  2522. * Returns a new Vector3 copied from the current Vector3.
  2523. */
  2524. Vector3.prototype.clone = function () {
  2525. return new Vector3(this.x, this.y, this.z);
  2526. };
  2527. /**
  2528. * Copies the passed vector coordinates to the current Vector3 ones.
  2529. * Returns the updated Vector3.
  2530. */
  2531. Vector3.prototype.copyFrom = function (source) {
  2532. this.x = source.x;
  2533. this.y = source.y;
  2534. this.z = source.z;
  2535. return this;
  2536. };
  2537. /**
  2538. * Copies the passed floats to the current Vector3 coordinates.
  2539. * Returns the updated Vector3.
  2540. */
  2541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2542. this.x = x;
  2543. this.y = y;
  2544. this.z = z;
  2545. return this;
  2546. };
  2547. /**
  2548. * Copies the passed floats to the current Vector3 coordinates.
  2549. * Returns the updated Vector3.
  2550. */
  2551. Vector3.prototype.set = function (x, y, z) {
  2552. return this.copyFromFloats(x, y, z);
  2553. };
  2554. // Statics
  2555. /**
  2556. *
  2557. */
  2558. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2559. var d0 = Vector3.Dot(vector0, axis) - size;
  2560. var d1 = Vector3.Dot(vector1, axis) - size;
  2561. var s = d0 / (d0 - d1);
  2562. return s;
  2563. };
  2564. /**
  2565. * Get angle between two vectors.
  2566. * @param vector0 angle between vector0 and vector1
  2567. * @param vector1 angle between vector0 and vector1
  2568. * @param normal direction of the normal.
  2569. * @return the angle between vector0 and vector1.
  2570. */
  2571. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2572. var v0 = vector0.clone().normalize();
  2573. var v1 = vector1.clone().normalize();
  2574. var dot = Vector3.Dot(v0, v1);
  2575. var n = Vector3.Cross(v0, v1);
  2576. if (Vector3.Dot(n, normal) > 0) {
  2577. return Math.acos(dot);
  2578. }
  2579. return -Math.acos(dot);
  2580. };
  2581. /**
  2582. * Returns a new Vector3 set from the index "offset" of the passed array.
  2583. */
  2584. Vector3.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2589. };
  2590. /**
  2591. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2592. * This function is deprecated. Use FromArray instead.
  2593. */
  2594. Vector3.FromFloatArray = function (array, offset) {
  2595. return Vector3.FromArray(array, offset);
  2596. };
  2597. /**
  2598. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2599. */
  2600. Vector3.FromArrayToRef = function (array, offset, result) {
  2601. result.x = array[offset];
  2602. result.y = array[offset + 1];
  2603. result.z = array[offset + 2];
  2604. };
  2605. /**
  2606. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2607. * This function is deprecated. Use FromArrayToRef instead.
  2608. */
  2609. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2610. return Vector3.FromArrayToRef(array, offset, result);
  2611. };
  2612. /**
  2613. * Sets the passed vector "result" with the passed floats.
  2614. */
  2615. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2616. result.x = x;
  2617. result.y = y;
  2618. result.z = z;
  2619. };
  2620. /**
  2621. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2622. */
  2623. Vector3.Zero = function () {
  2624. return new Vector3(0.0, 0.0, 0.0);
  2625. };
  2626. /**
  2627. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2628. */
  2629. Vector3.One = function () {
  2630. return new Vector3(1.0, 1.0, 1.0);
  2631. };
  2632. /**
  2633. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2634. */
  2635. Vector3.Up = function () {
  2636. return new Vector3(0.0, 1.0, 0.0);
  2637. };
  2638. /**
  2639. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2640. */
  2641. Vector3.Forward = function () {
  2642. return new Vector3(0.0, 0.0, 1.0);
  2643. };
  2644. /**
  2645. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2646. */
  2647. Vector3.Right = function () {
  2648. return new Vector3(1.0, 0.0, 0.0);
  2649. };
  2650. /**
  2651. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2652. */
  2653. Vector3.Left = function () {
  2654. return new Vector3(-1.0, 0.0, 0.0);
  2655. };
  2656. /**
  2657. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2658. * This method computes tranformed coordinates only, not transformed direction vectors.
  2659. */
  2660. Vector3.TransformCoordinates = function (vector, transformation) {
  2661. var result = Vector3.Zero();
  2662. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2663. return result;
  2664. };
  2665. /**
  2666. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2667. * This method computes tranformed coordinates only, not transformed direction vectors.
  2668. */
  2669. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2670. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2671. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2672. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2673. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2674. result.x = x / w;
  2675. result.y = y / w;
  2676. result.z = z / w;
  2677. };
  2678. /**
  2679. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2680. * This method computes tranformed coordinates only, not transformed direction vectors.
  2681. */
  2682. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2683. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2684. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2685. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2686. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2687. result.x = rx / rw;
  2688. result.y = ry / rw;
  2689. result.z = rz / rw;
  2690. };
  2691. /**
  2692. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2693. * This methods computes transformed normalized direction vectors only.
  2694. */
  2695. Vector3.TransformNormal = function (vector, transformation) {
  2696. var result = Vector3.Zero();
  2697. Vector3.TransformNormalToRef(vector, transformation, result);
  2698. return result;
  2699. };
  2700. /**
  2701. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2702. * This methods computes transformed normalized direction vectors only.
  2703. */
  2704. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2705. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2706. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2707. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2708. result.x = x;
  2709. result.y = y;
  2710. result.z = z;
  2711. };
  2712. /**
  2713. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2714. * This methods computes transformed normalized direction vectors only.
  2715. */
  2716. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2717. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2718. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2719. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2720. };
  2721. /**
  2722. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2723. */
  2724. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2725. var squared = amount * amount;
  2726. var cubed = amount * squared;
  2727. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2728. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2729. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2730. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2731. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2732. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2733. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2734. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2735. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2736. return new Vector3(x, y, z);
  2737. };
  2738. /**
  2739. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  2740. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2741. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2742. */
  2743. Vector3.Clamp = function (value, min, max) {
  2744. var x = value.x;
  2745. x = (x > max.x) ? max.x : x;
  2746. x = (x < min.x) ? min.x : x;
  2747. var y = value.y;
  2748. y = (y > max.y) ? max.y : y;
  2749. y = (y < min.y) ? min.y : y;
  2750. var z = value.z;
  2751. z = (z > max.z) ? max.z : z;
  2752. z = (z < min.z) ? min.z : z;
  2753. return new Vector3(x, y, z);
  2754. };
  2755. /**
  2756. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2757. */
  2758. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2759. var squared = amount * amount;
  2760. var cubed = amount * squared;
  2761. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2762. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2763. var part3 = (cubed - (2.0 * squared)) + amount;
  2764. var part4 = cubed - squared;
  2765. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2766. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2767. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2768. return new Vector3(x, y, z);
  2769. };
  2770. /**
  2771. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2772. */
  2773. Vector3.Lerp = function (start, end, amount) {
  2774. var result = new Vector3(0, 0, 0);
  2775. Vector3.LerpToRef(start, end, amount, result);
  2776. return result;
  2777. };
  2778. /**
  2779. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2780. */
  2781. Vector3.LerpToRef = function (start, end, amount, result) {
  2782. result.x = start.x + ((end.x - start.x) * amount);
  2783. result.y = start.y + ((end.y - start.y) * amount);
  2784. result.z = start.z + ((end.z - start.z) * amount);
  2785. };
  2786. /**
  2787. * Returns the dot product (float) between the vectors "left" and "right".
  2788. */
  2789. Vector3.Dot = function (left, right) {
  2790. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2791. };
  2792. /**
  2793. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2794. * The cross product is then orthogonal to both "left" and "right".
  2795. */
  2796. Vector3.Cross = function (left, right) {
  2797. var result = Vector3.Zero();
  2798. Vector3.CrossToRef(left, right, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed vector "result" with the cross product of "left" and "right".
  2803. * The cross product is then orthogonal to both "left" and "right".
  2804. */
  2805. Vector3.CrossToRef = function (left, right, result) {
  2806. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2807. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2808. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2809. result.copyFrom(MathTmp.Vector3[0]);
  2810. };
  2811. /**
  2812. * Returns a new Vector3 as the normalization of the passed vector.
  2813. */
  2814. Vector3.Normalize = function (vector) {
  2815. var result = Vector3.Zero();
  2816. Vector3.NormalizeToRef(vector, result);
  2817. return result;
  2818. };
  2819. /**
  2820. * Sets the passed vector "result" with the normalization of the passed first vector.
  2821. */
  2822. Vector3.NormalizeToRef = function (vector, result) {
  2823. result.copyFrom(vector);
  2824. result.normalize();
  2825. };
  2826. Vector3.Project = function (vector, world, transform, viewport) {
  2827. var cw = viewport.width;
  2828. var ch = viewport.height;
  2829. var cx = viewport.x;
  2830. var cy = viewport.y;
  2831. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2832. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  2833. var matrix = MathTmp.Matrix[0];
  2834. world.multiplyToRef(transform, matrix);
  2835. matrix.multiplyToRef(viewportMatrix, matrix);
  2836. return Vector3.TransformCoordinates(vector, matrix);
  2837. };
  2838. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2839. var matrix = MathTmp.Matrix[0];
  2840. world.multiplyToRef(transform, matrix);
  2841. matrix.invert();
  2842. source.x = source.x / viewportWidth * 2 - 1;
  2843. source.y = -(source.y / viewportHeight * 2 - 1);
  2844. var vector = Vector3.TransformCoordinates(source, matrix);
  2845. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2846. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2847. vector = vector.scale(1.0 / num);
  2848. }
  2849. return vector;
  2850. };
  2851. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2852. var result = Vector3.Zero();
  2853. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2854. return result;
  2855. };
  2856. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2857. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2858. };
  2859. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2860. var matrix = MathTmp.Matrix[0];
  2861. world.multiplyToRef(view, matrix);
  2862. matrix.multiplyToRef(projection, matrix);
  2863. matrix.invert();
  2864. var screenSource = MathTmp.Vector3[0];
  2865. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2866. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2867. screenSource.z = 2 * sourceZ - 1.0;
  2868. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2869. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2870. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2871. result.scaleInPlace(1.0 / num);
  2872. }
  2873. };
  2874. Vector3.Minimize = function (left, right) {
  2875. var min = left.clone();
  2876. min.MinimizeInPlace(right);
  2877. return min;
  2878. };
  2879. Vector3.Maximize = function (left, right) {
  2880. var max = left.clone();
  2881. max.MaximizeInPlace(right);
  2882. return max;
  2883. };
  2884. /**
  2885. * Returns the distance (float) between the vectors "value1" and "value2".
  2886. */
  2887. Vector3.Distance = function (value1, value2) {
  2888. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2889. };
  2890. /**
  2891. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2892. */
  2893. Vector3.DistanceSquared = function (value1, value2) {
  2894. var x = value1.x - value2.x;
  2895. var y = value1.y - value2.y;
  2896. var z = value1.z - value2.z;
  2897. return (x * x) + (y * y) + (z * z);
  2898. };
  2899. /**
  2900. * Returns a new Vector3 located at the center between "value1" and "value2".
  2901. */
  2902. Vector3.Center = function (value1, value2) {
  2903. var center = value1.add(value2);
  2904. center.scaleInPlace(0.5);
  2905. return center;
  2906. };
  2907. /**
  2908. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2909. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2910. * to something in order to rotate it from its local system to the given target system.
  2911. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2912. * Returns a new Vector3.
  2913. */
  2914. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2915. var rotation = Vector3.Zero();
  2916. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2917. return rotation;
  2918. };
  2919. /**
  2920. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2921. */
  2922. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2923. var quat = MathTmp.Quaternion[0];
  2924. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2925. quat.toEulerAnglesToRef(ref);
  2926. };
  2927. return Vector3;
  2928. }());
  2929. BABYLON.Vector3 = Vector3;
  2930. //Vector4 class created for EulerAngle class conversion to Quaternion
  2931. var Vector4 = /** @class */ (function () {
  2932. /**
  2933. * Creates a Vector4 object from the passed floats.
  2934. */
  2935. function Vector4(x, y, z, w) {
  2936. this.x = x;
  2937. this.y = y;
  2938. this.z = z;
  2939. this.w = w;
  2940. }
  2941. /**
  2942. * Returns the string with the Vector4 coordinates.
  2943. */
  2944. Vector4.prototype.toString = function () {
  2945. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2946. };
  2947. /**
  2948. * Returns the string "Vector4".
  2949. */
  2950. Vector4.prototype.getClassName = function () {
  2951. return "Vector4";
  2952. };
  2953. /**
  2954. * Returns the Vector4 hash code.
  2955. */
  2956. Vector4.prototype.getHashCode = function () {
  2957. var hash = this.x || 0;
  2958. hash = (hash * 397) ^ (this.y || 0);
  2959. hash = (hash * 397) ^ (this.z || 0);
  2960. hash = (hash * 397) ^ (this.w || 0);
  2961. return hash;
  2962. };
  2963. // Operators
  2964. /**
  2965. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2966. */
  2967. Vector4.prototype.asArray = function () {
  2968. var result = new Array();
  2969. this.toArray(result, 0);
  2970. return result;
  2971. };
  2972. /**
  2973. * Populates the passed array from the passed index with the Vector4 coordinates.
  2974. * Returns the Vector4.
  2975. */
  2976. Vector4.prototype.toArray = function (array, index) {
  2977. if (index === undefined) {
  2978. index = 0;
  2979. }
  2980. array[index] = this.x;
  2981. array[index + 1] = this.y;
  2982. array[index + 2] = this.z;
  2983. array[index + 3] = this.w;
  2984. return this;
  2985. };
  2986. /**
  2987. * Adds the passed vector to the current Vector4.
  2988. * Returns the updated Vector4.
  2989. */
  2990. Vector4.prototype.addInPlace = function (otherVector) {
  2991. this.x += otherVector.x;
  2992. this.y += otherVector.y;
  2993. this.z += otherVector.z;
  2994. this.w += otherVector.w;
  2995. return this;
  2996. };
  2997. /**
  2998. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2999. */
  3000. Vector4.prototype.add = function (otherVector) {
  3001. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3002. };
  3003. /**
  3004. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3005. * Returns the current Vector4.
  3006. */
  3007. Vector4.prototype.addToRef = function (otherVector, result) {
  3008. result.x = this.x + otherVector.x;
  3009. result.y = this.y + otherVector.y;
  3010. result.z = this.z + otherVector.z;
  3011. result.w = this.w + otherVector.w;
  3012. return this;
  3013. };
  3014. /**
  3015. * Subtract in place the passed vector from the current Vector4.
  3016. * Returns the updated Vector4.
  3017. */
  3018. Vector4.prototype.subtractInPlace = function (otherVector) {
  3019. this.x -= otherVector.x;
  3020. this.y -= otherVector.y;
  3021. this.z -= otherVector.z;
  3022. this.w -= otherVector.w;
  3023. return this;
  3024. };
  3025. /**
  3026. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3027. */
  3028. Vector4.prototype.subtract = function (otherVector) {
  3029. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3030. };
  3031. /**
  3032. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3033. * Returns the current Vector4.
  3034. */
  3035. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3036. result.x = this.x - otherVector.x;
  3037. result.y = this.y - otherVector.y;
  3038. result.z = this.z - otherVector.z;
  3039. result.w = this.w - otherVector.w;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3044. */
  3045. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3046. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3047. };
  3048. /**
  3049. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3050. * Returns the current Vector4.
  3051. */
  3052. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3053. result.x = this.x - x;
  3054. result.y = this.y - y;
  3055. result.z = this.z - z;
  3056. result.w = this.w - w;
  3057. return this;
  3058. };
  3059. /**
  3060. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3061. */
  3062. Vector4.prototype.negate = function () {
  3063. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3064. };
  3065. /**
  3066. * Multiplies the current Vector4 coordinates by scale (float).
  3067. * Returns the updated Vector4.
  3068. */
  3069. Vector4.prototype.scaleInPlace = function (scale) {
  3070. this.x *= scale;
  3071. this.y *= scale;
  3072. this.z *= scale;
  3073. this.w *= scale;
  3074. return this;
  3075. };
  3076. /**
  3077. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3078. */
  3079. Vector4.prototype.scale = function (scale) {
  3080. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3081. };
  3082. /**
  3083. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3084. * Returns the current Vector4.
  3085. */
  3086. Vector4.prototype.scaleToRef = function (scale, result) {
  3087. result.x = this.x * scale;
  3088. result.y = this.y * scale;
  3089. result.z = this.z * scale;
  3090. result.w = this.w * scale;
  3091. return this;
  3092. };
  3093. /**
  3094. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3095. */
  3096. Vector4.prototype.equals = function (otherVector) {
  3097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3098. };
  3099. /**
  3100. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3101. */
  3102. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3103. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3104. return otherVector
  3105. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3106. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3107. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3108. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3109. };
  3110. /**
  3111. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3112. */
  3113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3114. return this.x === x && this.y === y && this.z === z && this.w === w;
  3115. };
  3116. /**
  3117. * Multiplies in place the current Vector4 by the passed one.
  3118. * Returns the updated Vector4.
  3119. */
  3120. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3121. this.x *= otherVector.x;
  3122. this.y *= otherVector.y;
  3123. this.z *= otherVector.z;
  3124. this.w *= otherVector.w;
  3125. return this;
  3126. };
  3127. /**
  3128. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3129. */
  3130. Vector4.prototype.multiply = function (otherVector) {
  3131. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3132. };
  3133. /**
  3134. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3135. * Returns the current Vector4.
  3136. */
  3137. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3138. result.x = this.x * otherVector.x;
  3139. result.y = this.y * otherVector.y;
  3140. result.z = this.z * otherVector.z;
  3141. result.w = this.w * otherVector.w;
  3142. return this;
  3143. };
  3144. /**
  3145. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3146. */
  3147. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3148. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3149. };
  3150. /**
  3151. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3152. */
  3153. Vector4.prototype.divide = function (otherVector) {
  3154. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3155. };
  3156. /**
  3157. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3158. * Returns the current Vector4.
  3159. */
  3160. Vector4.prototype.divideToRef = function (otherVector, result) {
  3161. result.x = this.x / otherVector.x;
  3162. result.y = this.y / otherVector.y;
  3163. result.z = this.z / otherVector.z;
  3164. result.w = this.w / otherVector.w;
  3165. return this;
  3166. };
  3167. /**
  3168. * Divides the current Vector3 coordinates by the passed ones.
  3169. * Returns the updated Vector3.
  3170. */
  3171. Vector4.prototype.divideInPlace = function (otherVector) {
  3172. return this.divideToRef(otherVector, this);
  3173. };
  3174. /**
  3175. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3176. */
  3177. Vector4.prototype.MinimizeInPlace = function (other) {
  3178. if (other.x < this.x)
  3179. this.x = other.x;
  3180. if (other.y < this.y)
  3181. this.y = other.y;
  3182. if (other.z < this.z)
  3183. this.z = other.z;
  3184. if (other.w < this.w)
  3185. this.w = other.w;
  3186. return this;
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MaximizeInPlace = function (other) {
  3192. if (other.x > this.x)
  3193. this.x = other.x;
  3194. if (other.y > this.y)
  3195. this.y = other.y;
  3196. if (other.z > this.z)
  3197. this.z = other.z;
  3198. if (other.w > this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. // Properties
  3203. /**
  3204. * Returns the Vector4 length (float).
  3205. */
  3206. Vector4.prototype.length = function () {
  3207. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3208. };
  3209. /**
  3210. * Returns the Vector4 squared length (float).
  3211. */
  3212. Vector4.prototype.lengthSquared = function () {
  3213. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3214. };
  3215. // Methods
  3216. /**
  3217. * Normalizes in place the Vector4.
  3218. * Returns the updated Vector4.
  3219. */
  3220. Vector4.prototype.normalize = function () {
  3221. var len = this.length();
  3222. if (len === 0)
  3223. return this;
  3224. var num = 1.0 / len;
  3225. this.x *= num;
  3226. this.y *= num;
  3227. this.z *= num;
  3228. this.w *= num;
  3229. return this;
  3230. };
  3231. /**
  3232. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3233. */
  3234. Vector4.prototype.toVector3 = function () {
  3235. return new Vector3(this.x, this.y, this.z);
  3236. };
  3237. /**
  3238. * Returns a new Vector4 copied from the current one.
  3239. */
  3240. Vector4.prototype.clone = function () {
  3241. return new Vector4(this.x, this.y, this.z, this.w);
  3242. };
  3243. /**
  3244. * Updates the current Vector4 with the passed one coordinates.
  3245. * Returns the updated Vector4.
  3246. */
  3247. Vector4.prototype.copyFrom = function (source) {
  3248. this.x = source.x;
  3249. this.y = source.y;
  3250. this.z = source.z;
  3251. this.w = source.w;
  3252. return this;
  3253. };
  3254. /**
  3255. * Updates the current Vector4 coordinates with the passed floats.
  3256. * Returns the updated Vector4.
  3257. */
  3258. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3259. this.x = x;
  3260. this.y = y;
  3261. this.z = z;
  3262. this.w = w;
  3263. return this;
  3264. };
  3265. /**
  3266. * Updates the current Vector4 coordinates with the passed floats.
  3267. * Returns the updated Vector4.
  3268. */
  3269. Vector4.prototype.set = function (x, y, z, w) {
  3270. return this.copyFromFloats(x, y, z, w);
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Vector4 set from the starting index of the passed array.
  3275. */
  3276. Vector4.FromArray = function (array, offset) {
  3277. if (!offset) {
  3278. offset = 0;
  3279. }
  3280. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3281. };
  3282. /**
  3283. * Updates the passed vector "result" from the starting index of the passed array.
  3284. */
  3285. Vector4.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. result.w = array[offset + 3];
  3290. };
  3291. /**
  3292. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3293. */
  3294. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3295. Vector4.FromArrayToRef(array, offset, result);
  3296. };
  3297. /**
  3298. * Updates the passed vector "result" coordinates from the passed floats.
  3299. */
  3300. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. result.w = w;
  3305. };
  3306. /**
  3307. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3308. */
  3309. Vector4.Zero = function () {
  3310. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3314. */
  3315. Vector4.One = function () {
  3316. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3317. };
  3318. /**
  3319. * Returns a new normalized Vector4 from the passed one.
  3320. */
  3321. Vector4.Normalize = function (vector) {
  3322. var result = Vector4.Zero();
  3323. Vector4.NormalizeToRef(vector, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Updates the passed vector "result" from the normalization of the passed one.
  3328. */
  3329. Vector4.NormalizeToRef = function (vector, result) {
  3330. result.copyFrom(vector);
  3331. result.normalize();
  3332. };
  3333. Vector4.Minimize = function (left, right) {
  3334. var min = left.clone();
  3335. min.MinimizeInPlace(right);
  3336. return min;
  3337. };
  3338. Vector4.Maximize = function (left, right) {
  3339. var max = left.clone();
  3340. max.MaximizeInPlace(right);
  3341. return max;
  3342. };
  3343. /**
  3344. * Returns the distance (float) between the vectors "value1" and "value2".
  3345. */
  3346. Vector4.Distance = function (value1, value2) {
  3347. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3348. };
  3349. /**
  3350. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3351. */
  3352. Vector4.DistanceSquared = function (value1, value2) {
  3353. var x = value1.x - value2.x;
  3354. var y = value1.y - value2.y;
  3355. var z = value1.z - value2.z;
  3356. var w = value1.w - value2.w;
  3357. return (x * x) + (y * y) + (z * z) + (w * w);
  3358. };
  3359. /**
  3360. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3361. */
  3362. Vector4.Center = function (value1, value2) {
  3363. var center = value1.add(value2);
  3364. center.scaleInPlace(0.5);
  3365. return center;
  3366. };
  3367. /**
  3368. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3369. * This methods computes transformed normalized direction vectors only.
  3370. */
  3371. Vector4.TransformNormal = function (vector, transformation) {
  3372. var result = Vector4.Zero();
  3373. Vector4.TransformNormalToRef(vector, transformation, result);
  3374. return result;
  3375. };
  3376. /**
  3377. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3378. * This methods computes transformed normalized direction vectors only.
  3379. */
  3380. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3381. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3382. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3383. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3384. result.x = x;
  3385. result.y = y;
  3386. result.z = z;
  3387. result.w = vector.w;
  3388. };
  3389. /**
  3390. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3391. * This methods computes transformed normalized direction vectors only.
  3392. */
  3393. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3394. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3395. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3396. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3397. result.w = w;
  3398. };
  3399. return Vector4;
  3400. }());
  3401. BABYLON.Vector4 = Vector4;
  3402. var Size = /** @class */ (function () {
  3403. /**
  3404. * Creates a Size object from the passed width and height (floats).
  3405. */
  3406. function Size(width, height) {
  3407. this.width = width;
  3408. this.height = height;
  3409. }
  3410. // Returns a string with the Size width and height.
  3411. Size.prototype.toString = function () {
  3412. return "{W: " + this.width + ", H: " + this.height + "}";
  3413. };
  3414. /**
  3415. * Returns the string "Size"
  3416. */
  3417. Size.prototype.getClassName = function () {
  3418. return "Size";
  3419. };
  3420. /**
  3421. * Returns the Size hash code.
  3422. */
  3423. Size.prototype.getHashCode = function () {
  3424. var hash = this.width || 0;
  3425. hash = (hash * 397) ^ (this.height || 0);
  3426. return hash;
  3427. };
  3428. /**
  3429. * Updates the current size from the passed one.
  3430. * Returns the updated Size.
  3431. */
  3432. Size.prototype.copyFrom = function (src) {
  3433. this.width = src.width;
  3434. this.height = src.height;
  3435. };
  3436. /**
  3437. * Updates in place the current Size from the passed floats.
  3438. * Returns the updated Size.
  3439. */
  3440. Size.prototype.copyFromFloats = function (width, height) {
  3441. this.width = width;
  3442. this.height = height;
  3443. return this;
  3444. };
  3445. /**
  3446. * Updates in place the current Size from the passed floats.
  3447. * Returns the updated Size.
  3448. */
  3449. Size.prototype.set = function (width, height) {
  3450. return this.copyFromFloats(width, height);
  3451. };
  3452. /**
  3453. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3454. */
  3455. Size.prototype.multiplyByFloats = function (w, h) {
  3456. return new Size(this.width * w, this.height * h);
  3457. };
  3458. /**
  3459. * Returns a new Size copied from the passed one.
  3460. */
  3461. Size.prototype.clone = function () {
  3462. return new Size(this.width, this.height);
  3463. };
  3464. /**
  3465. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3466. */
  3467. Size.prototype.equals = function (other) {
  3468. if (!other) {
  3469. return false;
  3470. }
  3471. return (this.width === other.width) && (this.height === other.height);
  3472. };
  3473. Object.defineProperty(Size.prototype, "surface", {
  3474. /**
  3475. * Returns the surface of the Size : width * height (float).
  3476. */
  3477. get: function () {
  3478. return this.width * this.height;
  3479. },
  3480. enumerable: true,
  3481. configurable: true
  3482. });
  3483. /**
  3484. * Returns a new Size set to (0.0, 0.0)
  3485. */
  3486. Size.Zero = function () {
  3487. return new Size(0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Size set as the addition result of the current Size and the passed one.
  3491. */
  3492. Size.prototype.add = function (otherSize) {
  3493. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3494. return r;
  3495. };
  3496. /**
  3497. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3498. */
  3499. Size.prototype.subtract = function (otherSize) {
  3500. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3501. return r;
  3502. };
  3503. /**
  3504. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3505. */
  3506. Size.Lerp = function (start, end, amount) {
  3507. var w = start.width + ((end.width - start.width) * amount);
  3508. var h = start.height + ((end.height - start.height) * amount);
  3509. return new Size(w, h);
  3510. };
  3511. return Size;
  3512. }());
  3513. BABYLON.Size = Size;
  3514. var Quaternion = /** @class */ (function () {
  3515. /**
  3516. * Creates a new Quaternion from the passed floats.
  3517. */
  3518. function Quaternion(x, y, z, w) {
  3519. if (x === void 0) { x = 0.0; }
  3520. if (y === void 0) { y = 0.0; }
  3521. if (z === void 0) { z = 0.0; }
  3522. if (w === void 0) { w = 1.0; }
  3523. this.x = x;
  3524. this.y = y;
  3525. this.z = z;
  3526. this.w = w;
  3527. }
  3528. /**
  3529. * Returns a string with the Quaternion coordinates.
  3530. */
  3531. Quaternion.prototype.toString = function () {
  3532. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3533. };
  3534. /**
  3535. * Returns the string "Quaternion".
  3536. */
  3537. Quaternion.prototype.getClassName = function () {
  3538. return "Quaternion";
  3539. };
  3540. /**
  3541. * Returns the Quaternion hash code.
  3542. */
  3543. Quaternion.prototype.getHashCode = function () {
  3544. var hash = this.x || 0;
  3545. hash = (hash * 397) ^ (this.y || 0);
  3546. hash = (hash * 397) ^ (this.z || 0);
  3547. hash = (hash * 397) ^ (this.w || 0);
  3548. return hash;
  3549. };
  3550. /**
  3551. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3552. */
  3553. Quaternion.prototype.asArray = function () {
  3554. return [this.x, this.y, this.z, this.w];
  3555. };
  3556. /**
  3557. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3558. */
  3559. Quaternion.prototype.equals = function (otherQuaternion) {
  3560. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3561. };
  3562. /**
  3563. * Returns a new Quaternion copied from the current one.
  3564. */
  3565. Quaternion.prototype.clone = function () {
  3566. return new Quaternion(this.x, this.y, this.z, this.w);
  3567. };
  3568. /**
  3569. * Updates the current Quaternion from the passed one coordinates.
  3570. * Returns the updated Quaterion.
  3571. */
  3572. Quaternion.prototype.copyFrom = function (other) {
  3573. this.x = other.x;
  3574. this.y = other.y;
  3575. this.z = other.z;
  3576. this.w = other.w;
  3577. return this;
  3578. };
  3579. /**
  3580. * Updates the current Quaternion from the passed float coordinates.
  3581. * Returns the updated Quaterion.
  3582. */
  3583. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3584. this.x = x;
  3585. this.y = y;
  3586. this.z = z;
  3587. this.w = w;
  3588. return this;
  3589. };
  3590. /**
  3591. * Updates the current Quaternion from the passed float coordinates.
  3592. * Returns the updated Quaterion.
  3593. */
  3594. Quaternion.prototype.set = function (x, y, z, w) {
  3595. return this.copyFromFloats(x, y, z, w);
  3596. };
  3597. /**
  3598. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3599. */
  3600. Quaternion.prototype.add = function (other) {
  3601. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3602. };
  3603. /**
  3604. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3605. */
  3606. Quaternion.prototype.subtract = function (other) {
  3607. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3608. };
  3609. /**
  3610. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3611. */
  3612. Quaternion.prototype.scale = function (value) {
  3613. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3614. };
  3615. /**
  3616. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3617. */
  3618. Quaternion.prototype.multiply = function (q1) {
  3619. var result = new Quaternion(0, 0, 0, 1.0);
  3620. this.multiplyToRef(q1, result);
  3621. return result;
  3622. };
  3623. /**
  3624. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3625. * Returns the current Quaternion.
  3626. */
  3627. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3628. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3629. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3630. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3631. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3632. result.copyFromFloats(x, y, z, w);
  3633. return this;
  3634. };
  3635. /**
  3636. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3637. * Returns the updated Quaternion.
  3638. */
  3639. Quaternion.prototype.multiplyInPlace = function (q1) {
  3640. this.multiplyToRef(q1, this);
  3641. return this;
  3642. };
  3643. /**
  3644. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3645. * Returns the current Quaternion.
  3646. */
  3647. Quaternion.prototype.conjugateToRef = function (ref) {
  3648. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3649. return this;
  3650. };
  3651. /**
  3652. * Conjugates in place the current Quaternion.
  3653. * Returns the updated Quaternion.
  3654. */
  3655. Quaternion.prototype.conjugateInPlace = function () {
  3656. this.x *= -1;
  3657. this.y *= -1;
  3658. this.z *= -1;
  3659. return this;
  3660. };
  3661. /**
  3662. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3663. */
  3664. Quaternion.prototype.conjugate = function () {
  3665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3666. return result;
  3667. };
  3668. /**
  3669. * Returns the Quaternion length (float).
  3670. */
  3671. Quaternion.prototype.length = function () {
  3672. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3673. };
  3674. /**
  3675. * Normalize in place the current Quaternion.
  3676. * Returns the updated Quaternion.
  3677. */
  3678. Quaternion.prototype.normalize = function () {
  3679. var length = 1.0 / this.length();
  3680. this.x *= length;
  3681. this.y *= length;
  3682. this.z *= length;
  3683. this.w *= length;
  3684. return this;
  3685. };
  3686. /**
  3687. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3688. */
  3689. Quaternion.prototype.toEulerAngles = function (order) {
  3690. if (order === void 0) { order = "YZX"; }
  3691. var result = Vector3.Zero();
  3692. this.toEulerAnglesToRef(result, order);
  3693. return result;
  3694. };
  3695. /**
  3696. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3697. * Returns the current Quaternion.
  3698. */
  3699. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3700. if (order === void 0) { order = "YZX"; }
  3701. var qz = this.z;
  3702. var qx = this.x;
  3703. var qy = this.y;
  3704. var qw = this.w;
  3705. var sqw = qw * qw;
  3706. var sqz = qz * qz;
  3707. var sqx = qx * qx;
  3708. var sqy = qy * qy;
  3709. var zAxisY = qy * qz - qx * qw;
  3710. var limit = .4999999;
  3711. if (zAxisY < -limit) {
  3712. result.y = 2 * Math.atan2(qy, qw);
  3713. result.x = Math.PI / 2;
  3714. result.z = 0;
  3715. }
  3716. else if (zAxisY > limit) {
  3717. result.y = 2 * Math.atan2(qy, qw);
  3718. result.x = -Math.PI / 2;
  3719. result.z = 0;
  3720. }
  3721. else {
  3722. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3723. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3724. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3725. }
  3726. return this;
  3727. };
  3728. /**
  3729. * Updates the passed rotation matrix with the current Quaternion values.
  3730. * Returns the current Quaternion.
  3731. */
  3732. Quaternion.prototype.toRotationMatrix = function (result) {
  3733. var xx = this.x * this.x;
  3734. var yy = this.y * this.y;
  3735. var zz = this.z * this.z;
  3736. var xy = this.x * this.y;
  3737. var zw = this.z * this.w;
  3738. var zx = this.z * this.x;
  3739. var yw = this.y * this.w;
  3740. var yz = this.y * this.z;
  3741. var xw = this.x * this.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0;
  3754. result.m[12] = 0;
  3755. result.m[13] = 0;
  3756. result.m[14] = 0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. return this;
  3760. };
  3761. /**
  3762. * Updates the current Quaternion from the passed rotation matrix values.
  3763. * Returns the updated Quaternion.
  3764. */
  3765. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3766. Quaternion.FromRotationMatrixToRef(matrix, this);
  3767. return this;
  3768. };
  3769. // Statics
  3770. /**
  3771. * Returns a new Quaternion set from the passed rotation matrix values.
  3772. */
  3773. Quaternion.FromRotationMatrix = function (matrix) {
  3774. var result = new Quaternion();
  3775. Quaternion.FromRotationMatrixToRef(matrix, result);
  3776. return result;
  3777. };
  3778. /**
  3779. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3780. */
  3781. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3782. var data = matrix.m;
  3783. var m11 = data[0], m12 = data[4], m13 = data[8];
  3784. var m21 = data[1], m22 = data[5], m23 = data[9];
  3785. var m31 = data[2], m32 = data[6], m33 = data[10];
  3786. var trace = m11 + m22 + m33;
  3787. var s;
  3788. if (trace > 0) {
  3789. s = 0.5 / Math.sqrt(trace + 1.0);
  3790. result.w = 0.25 / s;
  3791. result.x = (m32 - m23) * s;
  3792. result.y = (m13 - m31) * s;
  3793. result.z = (m21 - m12) * s;
  3794. }
  3795. else if (m11 > m22 && m11 > m33) {
  3796. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3797. result.w = (m32 - m23) / s;
  3798. result.x = 0.25 * s;
  3799. result.y = (m12 + m21) / s;
  3800. result.z = (m13 + m31) / s;
  3801. }
  3802. else if (m22 > m33) {
  3803. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3804. result.w = (m13 - m31) / s;
  3805. result.x = (m12 + m21) / s;
  3806. result.y = 0.25 * s;
  3807. result.z = (m23 + m32) / s;
  3808. }
  3809. else {
  3810. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3811. result.w = (m21 - m12) / s;
  3812. result.x = (m13 + m31) / s;
  3813. result.y = (m23 + m32) / s;
  3814. result.z = 0.25 * s;
  3815. }
  3816. };
  3817. /**
  3818. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3819. */
  3820. Quaternion.Zero = function () {
  3821. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3822. };
  3823. /**
  3824. * Returns a new Quaternion as the inverted current Quaternion.
  3825. */
  3826. Quaternion.Inverse = function (q) {
  3827. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3828. };
  3829. /**
  3830. * Returns the identity Quaternion.
  3831. */
  3832. Quaternion.Identity = function () {
  3833. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3834. };
  3835. Quaternion.IsIdentity = function (quaternion) {
  3836. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3837. };
  3838. /**
  3839. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3840. */
  3841. Quaternion.RotationAxis = function (axis, angle) {
  3842. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3843. };
  3844. /**
  3845. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3846. */
  3847. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3848. var sin = Math.sin(angle / 2);
  3849. axis.normalize();
  3850. result.w = Math.cos(angle / 2);
  3851. result.x = axis.x * sin;
  3852. result.y = axis.y * sin;
  3853. result.z = axis.z * sin;
  3854. return result;
  3855. };
  3856. /**
  3857. * Retuns a new Quaternion set from the starting index of the passed array.
  3858. */
  3859. Quaternion.FromArray = function (array, offset) {
  3860. if (!offset) {
  3861. offset = 0;
  3862. }
  3863. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3864. };
  3865. /**
  3866. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3867. */
  3868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3869. var q = new Quaternion();
  3870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3871. return q;
  3872. };
  3873. /**
  3874. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3875. */
  3876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3878. var halfRoll = roll * 0.5;
  3879. var halfPitch = pitch * 0.5;
  3880. var halfYaw = yaw * 0.5;
  3881. var sinRoll = Math.sin(halfRoll);
  3882. var cosRoll = Math.cos(halfRoll);
  3883. var sinPitch = Math.sin(halfPitch);
  3884. var cosPitch = Math.cos(halfPitch);
  3885. var sinYaw = Math.sin(halfYaw);
  3886. var cosYaw = Math.cos(halfYaw);
  3887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3891. };
  3892. /**
  3893. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3894. */
  3895. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3896. var result = new Quaternion();
  3897. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3898. return result;
  3899. };
  3900. /**
  3901. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3902. */
  3903. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3904. // Produces a quaternion from Euler angles in the z-x-z orientation
  3905. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3906. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3907. var halfBeta = beta * 0.5;
  3908. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3909. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3910. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3911. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3912. };
  3913. /**
  3914. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3915. * cf to Vector3.RotationFromAxis() documentation.
  3916. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3917. */
  3918. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3919. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3920. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3921. return quat;
  3922. };
  3923. /**
  3924. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3925. * cf to Vector3.RotationFromAxis() documentation.
  3926. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3927. */
  3928. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3929. var rotMat = MathTmp.Matrix[0];
  3930. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3931. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3932. };
  3933. Quaternion.Slerp = function (left, right, amount) {
  3934. var result = Quaternion.Identity();
  3935. Quaternion.SlerpToRef(left, right, amount, result);
  3936. return result;
  3937. };
  3938. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3939. var num2;
  3940. var num3;
  3941. var num = amount;
  3942. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3943. var flag = false;
  3944. if (num4 < 0) {
  3945. flag = true;
  3946. num4 = -num4;
  3947. }
  3948. if (num4 > 0.999999) {
  3949. num3 = 1 - num;
  3950. num2 = flag ? -num : num;
  3951. }
  3952. else {
  3953. var num5 = Math.acos(num4);
  3954. var num6 = (1.0 / Math.sin(num5));
  3955. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3956. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3957. }
  3958. result.x = (num3 * left.x) + (num2 * right.x);
  3959. result.y = (num3 * left.y) + (num2 * right.y);
  3960. result.z = (num3 * left.z) + (num2 * right.z);
  3961. result.w = (num3 * left.w) + (num2 * right.w);
  3962. };
  3963. /**
  3964. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3965. */
  3966. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3967. var squared = amount * amount;
  3968. var cubed = amount * squared;
  3969. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3970. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3971. var part3 = (cubed - (2.0 * squared)) + amount;
  3972. var part4 = cubed - squared;
  3973. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3974. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3975. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3976. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3977. return new Quaternion(x, y, z, w);
  3978. };
  3979. return Quaternion;
  3980. }());
  3981. BABYLON.Quaternion = Quaternion;
  3982. var Matrix = /** @class */ (function () {
  3983. function Matrix() {
  3984. this._isIdentity = false;
  3985. this._isIdentityDirty = true;
  3986. this.m = new Float32Array(16);
  3987. this._markAsUpdated();
  3988. }
  3989. Matrix.prototype._markAsUpdated = function () {
  3990. this.updateFlag = Matrix._updateFlagSeed++;
  3991. this._isIdentityDirty = true;
  3992. };
  3993. // Properties
  3994. /**
  3995. * Boolean : True is the matrix is the identity matrix
  3996. */
  3997. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3998. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3999. if (this._isIdentityDirty) {
  4000. this._isIdentityDirty = false;
  4001. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4002. this._isIdentity = false;
  4003. }
  4004. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4005. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4006. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4007. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4008. this._isIdentity = false;
  4009. }
  4010. else {
  4011. this._isIdentity = true;
  4012. }
  4013. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4014. this._isIdentity = false;
  4015. }
  4016. }
  4017. return this._isIdentity;
  4018. };
  4019. /**
  4020. * Returns the matrix determinant (float).
  4021. */
  4022. Matrix.prototype.determinant = function () {
  4023. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4024. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4025. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4026. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4027. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4028. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4029. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4030. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4031. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4032. };
  4033. // Methods
  4034. /**
  4035. * Returns the matrix underlying array.
  4036. */
  4037. Matrix.prototype.toArray = function () {
  4038. return this.m;
  4039. };
  4040. /**
  4041. * Returns the matrix underlying array.
  4042. */
  4043. Matrix.prototype.asArray = function () {
  4044. return this.toArray();
  4045. };
  4046. /**
  4047. * Inverts in place the Matrix.
  4048. * Returns the Matrix inverted.
  4049. */
  4050. Matrix.prototype.invert = function () {
  4051. this.invertToRef(this);
  4052. return this;
  4053. };
  4054. /**
  4055. * Sets all the matrix elements to zero.
  4056. * Returns the Matrix.
  4057. */
  4058. Matrix.prototype.reset = function () {
  4059. for (var index = 0; index < 16; index++) {
  4060. this.m[index] = 0.0;
  4061. }
  4062. this._markAsUpdated();
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4067. */
  4068. Matrix.prototype.add = function (other) {
  4069. var result = new Matrix();
  4070. this.addToRef(other, result);
  4071. return result;
  4072. };
  4073. /**
  4074. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4075. * Returns the Matrix.
  4076. */
  4077. Matrix.prototype.addToRef = function (other, result) {
  4078. for (var index = 0; index < 16; index++) {
  4079. result.m[index] = this.m[index] + other.m[index];
  4080. }
  4081. result._markAsUpdated();
  4082. return this;
  4083. };
  4084. /**
  4085. * Adds in place the passed matrix to the current Matrix.
  4086. * Returns the updated Matrix.
  4087. */
  4088. Matrix.prototype.addToSelf = function (other) {
  4089. for (var index = 0; index < 16; index++) {
  4090. this.m[index] += other.m[index];
  4091. }
  4092. this._markAsUpdated();
  4093. return this;
  4094. };
  4095. /**
  4096. * Sets the passed matrix with the current inverted Matrix.
  4097. * Returns the unmodified current Matrix.
  4098. */
  4099. Matrix.prototype.invertToRef = function (other) {
  4100. var l1 = this.m[0];
  4101. var l2 = this.m[1];
  4102. var l3 = this.m[2];
  4103. var l4 = this.m[3];
  4104. var l5 = this.m[4];
  4105. var l6 = this.m[5];
  4106. var l7 = this.m[6];
  4107. var l8 = this.m[7];
  4108. var l9 = this.m[8];
  4109. var l10 = this.m[9];
  4110. var l11 = this.m[10];
  4111. var l12 = this.m[11];
  4112. var l13 = this.m[12];
  4113. var l14 = this.m[13];
  4114. var l15 = this.m[14];
  4115. var l16 = this.m[15];
  4116. var l17 = (l11 * l16) - (l12 * l15);
  4117. var l18 = (l10 * l16) - (l12 * l14);
  4118. var l19 = (l10 * l15) - (l11 * l14);
  4119. var l20 = (l9 * l16) - (l12 * l13);
  4120. var l21 = (l9 * l15) - (l11 * l13);
  4121. var l22 = (l9 * l14) - (l10 * l13);
  4122. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4123. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4124. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4125. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4126. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4127. var l28 = (l7 * l16) - (l8 * l15);
  4128. var l29 = (l6 * l16) - (l8 * l14);
  4129. var l30 = (l6 * l15) - (l7 * l14);
  4130. var l31 = (l5 * l16) - (l8 * l13);
  4131. var l32 = (l5 * l15) - (l7 * l13);
  4132. var l33 = (l5 * l14) - (l6 * l13);
  4133. var l34 = (l7 * l12) - (l8 * l11);
  4134. var l35 = (l6 * l12) - (l8 * l10);
  4135. var l36 = (l6 * l11) - (l7 * l10);
  4136. var l37 = (l5 * l12) - (l8 * l9);
  4137. var l38 = (l5 * l11) - (l7 * l9);
  4138. var l39 = (l5 * l10) - (l6 * l9);
  4139. other.m[0] = l23 * l27;
  4140. other.m[4] = l24 * l27;
  4141. other.m[8] = l25 * l27;
  4142. other.m[12] = l26 * l27;
  4143. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4144. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4145. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4146. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4147. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4148. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4149. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4150. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4151. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4152. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4153. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4154. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4155. other._markAsUpdated();
  4156. return this;
  4157. };
  4158. /**
  4159. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4160. * Returns the updated Matrix.
  4161. */
  4162. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4163. this.m[12] = x;
  4164. this.m[13] = y;
  4165. this.m[14] = z;
  4166. this._markAsUpdated();
  4167. return this;
  4168. };
  4169. /**
  4170. * Inserts the translation vector in the current Matrix.
  4171. * Returns the updated Matrix.
  4172. */
  4173. Matrix.prototype.setTranslation = function (vector3) {
  4174. this.m[12] = vector3.x;
  4175. this.m[13] = vector3.y;
  4176. this.m[14] = vector3.z;
  4177. this._markAsUpdated();
  4178. return this;
  4179. };
  4180. /**
  4181. * Returns a new Vector3 as the extracted translation from the Matrix.
  4182. */
  4183. Matrix.prototype.getTranslation = function () {
  4184. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4185. };
  4186. /**
  4187. * Fill a Vector3 with the extracted translation from the Matrix.
  4188. */
  4189. Matrix.prototype.getTranslationToRef = function (result) {
  4190. result.x = this.m[12];
  4191. result.y = this.m[13];
  4192. result.z = this.m[14];
  4193. return this;
  4194. };
  4195. /**
  4196. * Remove rotation and scaling part from the Matrix.
  4197. * Returns the updated Matrix.
  4198. */
  4199. Matrix.prototype.removeRotationAndScaling = function () {
  4200. this.setRowFromFloats(0, 1, 0, 0, 0);
  4201. this.setRowFromFloats(1, 0, 1, 0, 0);
  4202. this.setRowFromFloats(2, 0, 0, 1, 0);
  4203. return this;
  4204. };
  4205. /**
  4206. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4207. */
  4208. Matrix.prototype.multiply = function (other) {
  4209. var result = new Matrix();
  4210. this.multiplyToRef(other, result);
  4211. return result;
  4212. };
  4213. /**
  4214. * Updates the current Matrix from the passed one values.
  4215. * Returns the updated Matrix.
  4216. */
  4217. Matrix.prototype.copyFrom = function (other) {
  4218. for (var index = 0; index < 16; index++) {
  4219. this.m[index] = other.m[index];
  4220. }
  4221. this._markAsUpdated();
  4222. return this;
  4223. };
  4224. /**
  4225. * Populates the passed array from the starting index with the Matrix values.
  4226. * Returns the Matrix.
  4227. */
  4228. Matrix.prototype.copyToArray = function (array, offset) {
  4229. if (offset === void 0) { offset = 0; }
  4230. for (var index = 0; index < 16; index++) {
  4231. array[offset + index] = this.m[index];
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4237. */
  4238. Matrix.prototype.multiplyToRef = function (other, result) {
  4239. this.multiplyToArray(other, result.m, 0);
  4240. result._markAsUpdated();
  4241. return this;
  4242. };
  4243. /**
  4244. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4245. */
  4246. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4247. var tm0 = this.m[0];
  4248. var tm1 = this.m[1];
  4249. var tm2 = this.m[2];
  4250. var tm3 = this.m[3];
  4251. var tm4 = this.m[4];
  4252. var tm5 = this.m[5];
  4253. var tm6 = this.m[6];
  4254. var tm7 = this.m[7];
  4255. var tm8 = this.m[8];
  4256. var tm9 = this.m[9];
  4257. var tm10 = this.m[10];
  4258. var tm11 = this.m[11];
  4259. var tm12 = this.m[12];
  4260. var tm13 = this.m[13];
  4261. var tm14 = this.m[14];
  4262. var tm15 = this.m[15];
  4263. var om0 = other.m[0];
  4264. var om1 = other.m[1];
  4265. var om2 = other.m[2];
  4266. var om3 = other.m[3];
  4267. var om4 = other.m[4];
  4268. var om5 = other.m[5];
  4269. var om6 = other.m[6];
  4270. var om7 = other.m[7];
  4271. var om8 = other.m[8];
  4272. var om9 = other.m[9];
  4273. var om10 = other.m[10];
  4274. var om11 = other.m[11];
  4275. var om12 = other.m[12];
  4276. var om13 = other.m[13];
  4277. var om14 = other.m[14];
  4278. var om15 = other.m[15];
  4279. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4280. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4281. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4282. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4283. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4284. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4285. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4286. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4287. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4288. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4289. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4290. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4291. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4292. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4293. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4294. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4295. return this;
  4296. };
  4297. /**
  4298. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4299. */
  4300. Matrix.prototype.equals = function (value) {
  4301. return value &&
  4302. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4303. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4304. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4305. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4306. };
  4307. /**
  4308. * Returns a new Matrix from the current Matrix.
  4309. */
  4310. Matrix.prototype.clone = function () {
  4311. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  4312. };
  4313. /**
  4314. * Returns the string "Matrix"
  4315. */
  4316. Matrix.prototype.getClassName = function () {
  4317. return "Matrix";
  4318. };
  4319. /**
  4320. * Returns the Matrix hash code.
  4321. */
  4322. Matrix.prototype.getHashCode = function () {
  4323. var hash = this.m[0] || 0;
  4324. for (var i = 1; i < 16; i++) {
  4325. hash = (hash * 397) ^ (this.m[i] || 0);
  4326. }
  4327. return hash;
  4328. };
  4329. /**
  4330. * Decomposes the current Matrix into :
  4331. * - a scale vector3 passed as a reference to update,
  4332. * - a rotation quaternion passed as a reference to update,
  4333. * - a translation vector3 passed as a reference to update.
  4334. * Returns the true if operation was successful.
  4335. */
  4336. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4337. translation.x = this.m[12];
  4338. translation.y = this.m[13];
  4339. translation.z = this.m[14];
  4340. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4341. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4342. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4343. if (this.determinant() <= 0) {
  4344. scale.y *= -1;
  4345. }
  4346. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4347. rotation.x = 0;
  4348. rotation.y = 0;
  4349. rotation.z = 0;
  4350. rotation.w = 1;
  4351. return false;
  4352. }
  4353. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  4354. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4355. return true;
  4356. };
  4357. /**
  4358. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4359. */
  4360. Matrix.prototype.getRotationMatrix = function () {
  4361. var result = Matrix.Identity();
  4362. this.getRotationMatrixToRef(result);
  4363. return result;
  4364. };
  4365. /**
  4366. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4367. * Returns the current Matrix.
  4368. */
  4369. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4370. var m = this.m;
  4371. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4372. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4373. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4374. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4375. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4376. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4377. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  4378. return this;
  4379. };
  4380. // Statics
  4381. /**
  4382. * Returns a new Matrix set from the starting index of the passed array.
  4383. */
  4384. Matrix.FromArray = function (array, offset) {
  4385. var result = new Matrix();
  4386. if (!offset) {
  4387. offset = 0;
  4388. }
  4389. Matrix.FromArrayToRef(array, offset, result);
  4390. return result;
  4391. };
  4392. /**
  4393. * Sets the passed "result" matrix from the starting index of the passed array.
  4394. */
  4395. Matrix.FromArrayToRef = function (array, offset, result) {
  4396. for (var index = 0; index < 16; index++) {
  4397. result.m[index] = array[index + offset];
  4398. }
  4399. result._markAsUpdated();
  4400. };
  4401. /**
  4402. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4403. */
  4404. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4405. for (var index = 0; index < 16; index++) {
  4406. result.m[index] = array[index + offset] * scale;
  4407. }
  4408. result._markAsUpdated();
  4409. };
  4410. /**
  4411. * Sets the passed matrix "result" with the 16 passed floats.
  4412. */
  4413. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4414. result.m[0] = initialM11;
  4415. result.m[1] = initialM12;
  4416. result.m[2] = initialM13;
  4417. result.m[3] = initialM14;
  4418. result.m[4] = initialM21;
  4419. result.m[5] = initialM22;
  4420. result.m[6] = initialM23;
  4421. result.m[7] = initialM24;
  4422. result.m[8] = initialM31;
  4423. result.m[9] = initialM32;
  4424. result.m[10] = initialM33;
  4425. result.m[11] = initialM34;
  4426. result.m[12] = initialM41;
  4427. result.m[13] = initialM42;
  4428. result.m[14] = initialM43;
  4429. result.m[15] = initialM44;
  4430. result._markAsUpdated();
  4431. };
  4432. /**
  4433. * Returns the index-th row of the current matrix as a new Vector4.
  4434. */
  4435. Matrix.prototype.getRow = function (index) {
  4436. if (index < 0 || index > 3) {
  4437. return null;
  4438. }
  4439. var i = index * 4;
  4440. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4441. };
  4442. /**
  4443. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4444. * Returns the updated Matrix.
  4445. */
  4446. Matrix.prototype.setRow = function (index, row) {
  4447. if (index < 0 || index > 3) {
  4448. return this;
  4449. }
  4450. var i = index * 4;
  4451. this.m[i + 0] = row.x;
  4452. this.m[i + 1] = row.y;
  4453. this.m[i + 2] = row.z;
  4454. this.m[i + 3] = row.w;
  4455. this._markAsUpdated();
  4456. return this;
  4457. };
  4458. /**
  4459. * Compute the transpose of the matrix.
  4460. * Returns a new Matrix.
  4461. */
  4462. Matrix.prototype.transpose = function () {
  4463. return Matrix.Transpose(this);
  4464. };
  4465. /**
  4466. * Compute the transpose of the matrix.
  4467. * Returns the current matrix.
  4468. */
  4469. Matrix.prototype.transposeToRef = function (result) {
  4470. Matrix.TransposeToRef(this, result);
  4471. return this;
  4472. };
  4473. /**
  4474. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4475. * Returns the updated Matrix.
  4476. */
  4477. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4478. if (index < 0 || index > 3) {
  4479. return this;
  4480. }
  4481. var i = index * 4;
  4482. this.m[i + 0] = x;
  4483. this.m[i + 1] = y;
  4484. this.m[i + 2] = z;
  4485. this.m[i + 3] = w;
  4486. this._markAsUpdated();
  4487. return this;
  4488. };
  4489. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4490. /**
  4491. * Static identity matrix to be used as readonly matrix
  4492. * Must not be updated.
  4493. */
  4494. get: function () {
  4495. return Matrix._identityReadOnly;
  4496. },
  4497. enumerable: true,
  4498. configurable: true
  4499. });
  4500. /**
  4501. * Returns a new Matrix set from the 16 passed floats.
  4502. */
  4503. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4504. var result = new Matrix();
  4505. result.m[0] = initialM11;
  4506. result.m[1] = initialM12;
  4507. result.m[2] = initialM13;
  4508. result.m[3] = initialM14;
  4509. result.m[4] = initialM21;
  4510. result.m[5] = initialM22;
  4511. result.m[6] = initialM23;
  4512. result.m[7] = initialM24;
  4513. result.m[8] = initialM31;
  4514. result.m[9] = initialM32;
  4515. result.m[10] = initialM33;
  4516. result.m[11] = initialM34;
  4517. result.m[12] = initialM41;
  4518. result.m[13] = initialM42;
  4519. result.m[14] = initialM43;
  4520. result.m[15] = initialM44;
  4521. return result;
  4522. };
  4523. /**
  4524. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4525. */
  4526. Matrix.Compose = function (scale, rotation, translation) {
  4527. var result = Matrix.Identity();
  4528. Matrix.ComposeToRef(scale, rotation, translation, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4533. */
  4534. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4535. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4536. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4537. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4538. result.setTranslation(translation);
  4539. };
  4540. /**
  4541. * Returns a new indentity Matrix.
  4542. */
  4543. Matrix.Identity = function () {
  4544. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  4545. };
  4546. /**
  4547. * Sets the passed "result" as an identity matrix.
  4548. */
  4549. Matrix.IdentityToRef = function (result) {
  4550. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  4551. };
  4552. /**
  4553. * Returns a new zero Matrix.
  4554. */
  4555. Matrix.Zero = function () {
  4556. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  4557. };
  4558. /**
  4559. * Returns a new rotation matrix for "angle" radians around the X axis.
  4560. */
  4561. Matrix.RotationX = function (angle) {
  4562. var result = new Matrix();
  4563. Matrix.RotationXToRef(angle, result);
  4564. return result;
  4565. };
  4566. /**
  4567. * Returns a new Matrix as the passed inverted one.
  4568. */
  4569. Matrix.Invert = function (source) {
  4570. var result = new Matrix();
  4571. source.invertToRef(result);
  4572. return result;
  4573. };
  4574. /**
  4575. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4576. */
  4577. Matrix.RotationXToRef = function (angle, result) {
  4578. var s = Math.sin(angle);
  4579. var c = Math.cos(angle);
  4580. result.m[0] = 1.0;
  4581. result.m[15] = 1.0;
  4582. result.m[5] = c;
  4583. result.m[10] = c;
  4584. result.m[9] = -s;
  4585. result.m[6] = s;
  4586. result.m[1] = 0.0;
  4587. result.m[2] = 0.0;
  4588. result.m[3] = 0.0;
  4589. result.m[4] = 0.0;
  4590. result.m[7] = 0.0;
  4591. result.m[8] = 0.0;
  4592. result.m[11] = 0.0;
  4593. result.m[12] = 0.0;
  4594. result.m[13] = 0.0;
  4595. result.m[14] = 0.0;
  4596. result._markAsUpdated();
  4597. };
  4598. /**
  4599. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4600. */
  4601. Matrix.RotationY = function (angle) {
  4602. var result = new Matrix();
  4603. Matrix.RotationYToRef(angle, result);
  4604. return result;
  4605. };
  4606. /**
  4607. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4608. */
  4609. Matrix.RotationYToRef = function (angle, result) {
  4610. var s = Math.sin(angle);
  4611. var c = Math.cos(angle);
  4612. result.m[5] = 1.0;
  4613. result.m[15] = 1.0;
  4614. result.m[0] = c;
  4615. result.m[2] = -s;
  4616. result.m[8] = s;
  4617. result.m[10] = c;
  4618. result.m[1] = 0.0;
  4619. result.m[3] = 0.0;
  4620. result.m[4] = 0.0;
  4621. result.m[6] = 0.0;
  4622. result.m[7] = 0.0;
  4623. result.m[9] = 0.0;
  4624. result.m[11] = 0.0;
  4625. result.m[12] = 0.0;
  4626. result.m[13] = 0.0;
  4627. result.m[14] = 0.0;
  4628. result._markAsUpdated();
  4629. };
  4630. /**
  4631. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4632. */
  4633. Matrix.RotationZ = function (angle) {
  4634. var result = new Matrix();
  4635. Matrix.RotationZToRef(angle, result);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4640. */
  4641. Matrix.RotationZToRef = function (angle, result) {
  4642. var s = Math.sin(angle);
  4643. var c = Math.cos(angle);
  4644. result.m[10] = 1.0;
  4645. result.m[15] = 1.0;
  4646. result.m[0] = c;
  4647. result.m[1] = s;
  4648. result.m[4] = -s;
  4649. result.m[5] = c;
  4650. result.m[2] = 0.0;
  4651. result.m[3] = 0.0;
  4652. result.m[6] = 0.0;
  4653. result.m[7] = 0.0;
  4654. result.m[8] = 0.0;
  4655. result.m[9] = 0.0;
  4656. result.m[11] = 0.0;
  4657. result.m[12] = 0.0;
  4658. result.m[13] = 0.0;
  4659. result.m[14] = 0.0;
  4660. result._markAsUpdated();
  4661. };
  4662. /**
  4663. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4664. */
  4665. Matrix.RotationAxis = function (axis, angle) {
  4666. var result = Matrix.Zero();
  4667. Matrix.RotationAxisToRef(axis, angle, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4672. */
  4673. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4674. var s = Math.sin(-angle);
  4675. var c = Math.cos(-angle);
  4676. var c1 = 1 - c;
  4677. axis.normalize();
  4678. result.m[0] = (axis.x * axis.x) * c1 + c;
  4679. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4680. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4681. result.m[3] = 0.0;
  4682. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4683. result.m[5] = (axis.y * axis.y) * c1 + c;
  4684. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4685. result.m[7] = 0.0;
  4686. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4687. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4688. result.m[10] = (axis.z * axis.z) * c1 + c;
  4689. result.m[11] = 0.0;
  4690. result.m[15] = 1.0;
  4691. result._markAsUpdated();
  4692. };
  4693. /**
  4694. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4695. */
  4696. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4697. var result = new Matrix();
  4698. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4699. return result;
  4700. };
  4701. /**
  4702. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4703. */
  4704. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4705. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4706. this._tempQuaternion.toRotationMatrix(result);
  4707. };
  4708. /**
  4709. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4710. */
  4711. Matrix.Scaling = function (x, y, z) {
  4712. var result = Matrix.Zero();
  4713. Matrix.ScalingToRef(x, y, z, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4718. */
  4719. Matrix.ScalingToRef = function (x, y, z, result) {
  4720. result.m[0] = x;
  4721. result.m[1] = 0.0;
  4722. result.m[2] = 0.0;
  4723. result.m[3] = 0.0;
  4724. result.m[4] = 0.0;
  4725. result.m[5] = y;
  4726. result.m[6] = 0.0;
  4727. result.m[7] = 0.0;
  4728. result.m[8] = 0.0;
  4729. result.m[9] = 0.0;
  4730. result.m[10] = z;
  4731. result.m[11] = 0.0;
  4732. result.m[12] = 0.0;
  4733. result.m[13] = 0.0;
  4734. result.m[14] = 0.0;
  4735. result.m[15] = 1.0;
  4736. result._markAsUpdated();
  4737. };
  4738. /**
  4739. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4740. */
  4741. Matrix.Translation = function (x, y, z) {
  4742. var result = Matrix.Identity();
  4743. Matrix.TranslationToRef(x, y, z, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4748. */
  4749. Matrix.TranslationToRef = function (x, y, z, result) {
  4750. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  4751. };
  4752. /**
  4753. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4754. */
  4755. Matrix.Lerp = function (startValue, endValue, gradient) {
  4756. var result = Matrix.Zero();
  4757. for (var index = 0; index < 16; index++) {
  4758. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4759. }
  4760. result._markAsUpdated();
  4761. return result;
  4762. };
  4763. /**
  4764. * Returns a new Matrix whose values are computed by :
  4765. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4766. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4767. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4768. */
  4769. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4770. var startScale = new Vector3(0, 0, 0);
  4771. var startRotation = new Quaternion();
  4772. var startTranslation = new Vector3(0, 0, 0);
  4773. startValue.decompose(startScale, startRotation, startTranslation);
  4774. var endScale = new Vector3(0, 0, 0);
  4775. var endRotation = new Quaternion();
  4776. var endTranslation = new Vector3(0, 0, 0);
  4777. endValue.decompose(endScale, endRotation, endTranslation);
  4778. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4779. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4780. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4781. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4782. };
  4783. /**
  4784. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4785. * This methods works for a Left-Handed system.
  4786. */
  4787. Matrix.LookAtLH = function (eye, target, up) {
  4788. var result = Matrix.Zero();
  4789. Matrix.LookAtLHToRef(eye, target, up, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4794. * This methods works for a Left-Handed system.
  4795. */
  4796. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4797. // Z axis
  4798. target.subtractToRef(eye, this._zAxis);
  4799. this._zAxis.normalize();
  4800. // X axis
  4801. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4802. if (this._xAxis.lengthSquared() === 0) {
  4803. this._xAxis.x = 1.0;
  4804. }
  4805. else {
  4806. this._xAxis.normalize();
  4807. }
  4808. // Y axis
  4809. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4810. this._yAxis.normalize();
  4811. // Eye angles
  4812. var ex = -Vector3.Dot(this._xAxis, eye);
  4813. var ey = -Vector3.Dot(this._yAxis, eye);
  4814. var ez = -Vector3.Dot(this._zAxis, eye);
  4815. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  4816. };
  4817. /**
  4818. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4819. * This methods works for a Right-Handed system.
  4820. */
  4821. Matrix.LookAtRH = function (eye, target, up) {
  4822. var result = Matrix.Zero();
  4823. Matrix.LookAtRHToRef(eye, target, up, result);
  4824. return result;
  4825. };
  4826. /**
  4827. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4828. * This methods works for a Left-Handed system.
  4829. */
  4830. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4831. // Z axis
  4832. eye.subtractToRef(target, this._zAxis);
  4833. this._zAxis.normalize();
  4834. // X axis
  4835. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4836. if (this._xAxis.lengthSquared() === 0) {
  4837. this._xAxis.x = 1.0;
  4838. }
  4839. else {
  4840. this._xAxis.normalize();
  4841. }
  4842. // Y axis
  4843. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4844. this._yAxis.normalize();
  4845. // Eye angles
  4846. var ex = -Vector3.Dot(this._xAxis, eye);
  4847. var ey = -Vector3.Dot(this._yAxis, eye);
  4848. var ez = -Vector3.Dot(this._zAxis, eye);
  4849. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  4850. };
  4851. /**
  4852. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4853. */
  4854. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4855. var matrix = Matrix.Zero();
  4856. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4857. return matrix;
  4858. };
  4859. /**
  4860. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4861. */
  4862. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4863. var n = znear;
  4864. var f = zfar;
  4865. var a = 2.0 / width;
  4866. var b = 2.0 / height;
  4867. var c = 2.0 / (f - n);
  4868. var d = -(f + n) / (f - n);
  4869. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  4870. };
  4871. /**
  4872. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4873. */
  4874. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4875. var matrix = Matrix.Zero();
  4876. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4877. return matrix;
  4878. };
  4879. /**
  4880. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4881. */
  4882. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4883. var n = znear;
  4884. var f = zfar;
  4885. var a = 2.0 / (right - left);
  4886. var b = 2.0 / (top - bottom);
  4887. var c = 2.0 / (f - n);
  4888. var d = -(f + n) / (f - n);
  4889. var i0 = (left + right) / (left - right);
  4890. var i1 = (top + bottom) / (bottom - top);
  4891. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  4892. };
  4893. /**
  4894. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4895. */
  4896. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4897. var matrix = Matrix.Zero();
  4898. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4899. return matrix;
  4900. };
  4901. /**
  4902. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4903. */
  4904. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4905. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4906. result.m[10] *= -1.0;
  4907. };
  4908. /**
  4909. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4910. */
  4911. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4912. var matrix = Matrix.Zero();
  4913. var n = znear;
  4914. var f = zfar;
  4915. var a = 2.0 * n / width;
  4916. var b = 2.0 * n / height;
  4917. var c = (f + n) / (f - n);
  4918. var d = -2.0 * f * n / (f - n);
  4919. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  4920. return matrix;
  4921. };
  4922. /**
  4923. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4924. */
  4925. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4928. return matrix;
  4929. };
  4930. /**
  4931. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4932. */
  4933. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4934. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4935. var n = znear;
  4936. var f = zfar;
  4937. var t = 1.0 / (Math.tan(fov * 0.5));
  4938. var a = isVerticalFovFixed ? (t / aspect) : t;
  4939. var b = isVerticalFovFixed ? t : (t * aspect);
  4940. var c = (f + n) / (f - n);
  4941. var d = -2.0 * f * n / (f - n);
  4942. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  4943. };
  4944. /**
  4945. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4946. */
  4947. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4948. var matrix = Matrix.Zero();
  4949. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4950. return matrix;
  4951. };
  4952. /**
  4953. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4954. */
  4955. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4956. //alternatively this could be expressed as:
  4957. // m = PerspectiveFovLHToRef
  4958. // m[10] *= -1.0;
  4959. // m[11] *= -1.0;
  4960. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4961. var n = znear;
  4962. var f = zfar;
  4963. var t = 1.0 / (Math.tan(fov * 0.5));
  4964. var a = isVerticalFovFixed ? (t / aspect) : t;
  4965. var b = isVerticalFovFixed ? t : (t * aspect);
  4966. var c = -(f + n) / (f - n);
  4967. var d = -2 * f * n / (f - n);
  4968. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  4969. };
  4970. /**
  4971. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4972. */
  4973. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4974. if (rightHanded === void 0) { rightHanded = false; }
  4975. var rightHandedFactor = rightHanded ? -1 : 1;
  4976. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4977. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4978. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4979. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4980. var xScale = 2.0 / (leftTan + rightTan);
  4981. var yScale = 2.0 / (upTan + downTan);
  4982. result.m[0] = xScale;
  4983. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4984. result.m[5] = yScale;
  4985. result.m[6] = result.m[7] = 0.0;
  4986. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4987. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4988. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4989. result.m[10] = -zfar / (znear - zfar);
  4990. result.m[11] = 1.0 * rightHandedFactor;
  4991. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4992. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4993. // result.m[14] = (znear * zfar) / (znear - zfar);
  4994. result._markAsUpdated();
  4995. };
  4996. /**
  4997. * Returns the final transformation matrix : world * view * projection * viewport
  4998. */
  4999. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5000. var cw = viewport.width;
  5001. var ch = viewport.height;
  5002. var cx = viewport.x;
  5003. var cy = viewport.y;
  5004. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5005. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5006. };
  5007. /**
  5008. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5009. */
  5010. Matrix.GetAsMatrix2x2 = function (matrix) {
  5011. return new Float32Array([
  5012. matrix.m[0], matrix.m[1],
  5013. matrix.m[4], matrix.m[5]
  5014. ]);
  5015. };
  5016. /**
  5017. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5018. */
  5019. Matrix.GetAsMatrix3x3 = function (matrix) {
  5020. return new Float32Array([
  5021. matrix.m[0], matrix.m[1], matrix.m[2],
  5022. matrix.m[4], matrix.m[5], matrix.m[6],
  5023. matrix.m[8], matrix.m[9], matrix.m[10]
  5024. ]);
  5025. };
  5026. /**
  5027. * Compute the transpose of the passed Matrix.
  5028. * Returns a new Matrix.
  5029. */
  5030. Matrix.Transpose = function (matrix) {
  5031. var result = new Matrix();
  5032. Matrix.TransposeToRef(matrix, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5037. */
  5038. Matrix.TransposeToRef = function (matrix, result) {
  5039. result.m[0] = matrix.m[0];
  5040. result.m[1] = matrix.m[4];
  5041. result.m[2] = matrix.m[8];
  5042. result.m[3] = matrix.m[12];
  5043. result.m[4] = matrix.m[1];
  5044. result.m[5] = matrix.m[5];
  5045. result.m[6] = matrix.m[9];
  5046. result.m[7] = matrix.m[13];
  5047. result.m[8] = matrix.m[2];
  5048. result.m[9] = matrix.m[6];
  5049. result.m[10] = matrix.m[10];
  5050. result.m[11] = matrix.m[14];
  5051. result.m[12] = matrix.m[3];
  5052. result.m[13] = matrix.m[7];
  5053. result.m[14] = matrix.m[11];
  5054. result.m[15] = matrix.m[15];
  5055. };
  5056. /**
  5057. * Returns a new Matrix as the reflection matrix across the passed plane.
  5058. */
  5059. Matrix.Reflection = function (plane) {
  5060. var matrix = new Matrix();
  5061. Matrix.ReflectionToRef(plane, matrix);
  5062. return matrix;
  5063. };
  5064. /**
  5065. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5066. */
  5067. Matrix.ReflectionToRef = function (plane, result) {
  5068. plane.normalize();
  5069. var x = plane.normal.x;
  5070. var y = plane.normal.y;
  5071. var z = plane.normal.z;
  5072. var temp = -2 * x;
  5073. var temp2 = -2 * y;
  5074. var temp3 = -2 * z;
  5075. result.m[0] = (temp * x) + 1;
  5076. result.m[1] = temp2 * x;
  5077. result.m[2] = temp3 * x;
  5078. result.m[3] = 0.0;
  5079. result.m[4] = temp * y;
  5080. result.m[5] = (temp2 * y) + 1;
  5081. result.m[6] = temp3 * y;
  5082. result.m[7] = 0.0;
  5083. result.m[8] = temp * z;
  5084. result.m[9] = temp2 * z;
  5085. result.m[10] = (temp3 * z) + 1;
  5086. result.m[11] = 0.0;
  5087. result.m[12] = temp * plane.d;
  5088. result.m[13] = temp2 * plane.d;
  5089. result.m[14] = temp3 * plane.d;
  5090. result.m[15] = 1.0;
  5091. result._markAsUpdated();
  5092. };
  5093. /**
  5094. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5095. */
  5096. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5097. result.m[0] = xaxis.x;
  5098. result.m[1] = xaxis.y;
  5099. result.m[2] = xaxis.z;
  5100. result.m[3] = 0.0;
  5101. result.m[4] = yaxis.x;
  5102. result.m[5] = yaxis.y;
  5103. result.m[6] = yaxis.z;
  5104. result.m[7] = 0.0;
  5105. result.m[8] = zaxis.x;
  5106. result.m[9] = zaxis.y;
  5107. result.m[10] = zaxis.z;
  5108. result.m[11] = 0.0;
  5109. result.m[12] = 0.0;
  5110. result.m[13] = 0.0;
  5111. result.m[14] = 0.0;
  5112. result.m[15] = 1.0;
  5113. result._markAsUpdated();
  5114. };
  5115. /**
  5116. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5117. */
  5118. Matrix.FromQuaternionToRef = function (quat, result) {
  5119. var xx = quat.x * quat.x;
  5120. var yy = quat.y * quat.y;
  5121. var zz = quat.z * quat.z;
  5122. var xy = quat.x * quat.y;
  5123. var zw = quat.z * quat.w;
  5124. var zx = quat.z * quat.x;
  5125. var yw = quat.y * quat.w;
  5126. var yz = quat.y * quat.z;
  5127. var xw = quat.x * quat.w;
  5128. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5129. result.m[1] = 2.0 * (xy + zw);
  5130. result.m[2] = 2.0 * (zx - yw);
  5131. result.m[3] = 0.0;
  5132. result.m[4] = 2.0 * (xy - zw);
  5133. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5134. result.m[6] = 2.0 * (yz + xw);
  5135. result.m[7] = 0.0;
  5136. result.m[8] = 2.0 * (zx + yw);
  5137. result.m[9] = 2.0 * (yz - xw);
  5138. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5139. result.m[11] = 0.0;
  5140. result.m[12] = 0.0;
  5141. result.m[13] = 0.0;
  5142. result.m[14] = 0.0;
  5143. result.m[15] = 1.0;
  5144. result._markAsUpdated();
  5145. };
  5146. Matrix._tempQuaternion = new Quaternion();
  5147. Matrix._xAxis = Vector3.Zero();
  5148. Matrix._yAxis = Vector3.Zero();
  5149. Matrix._zAxis = Vector3.Zero();
  5150. Matrix._updateFlagSeed = 0;
  5151. Matrix._identityReadOnly = Matrix.Identity();
  5152. return Matrix;
  5153. }());
  5154. BABYLON.Matrix = Matrix;
  5155. var Plane = /** @class */ (function () {
  5156. /**
  5157. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5158. */
  5159. function Plane(a, b, c, d) {
  5160. this.normal = new Vector3(a, b, c);
  5161. this.d = d;
  5162. }
  5163. /**
  5164. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5165. */
  5166. Plane.prototype.asArray = function () {
  5167. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5168. };
  5169. // Methods
  5170. /**
  5171. * Returns a new plane copied from the current Plane.
  5172. */
  5173. Plane.prototype.clone = function () {
  5174. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5175. };
  5176. /**
  5177. * Returns the string "Plane".
  5178. */
  5179. Plane.prototype.getClassName = function () {
  5180. return "Plane";
  5181. };
  5182. /**
  5183. * Returns the Plane hash code.
  5184. */
  5185. Plane.prototype.getHashCode = function () {
  5186. var hash = this.normal.getHashCode();
  5187. hash = (hash * 397) ^ (this.d || 0);
  5188. return hash;
  5189. };
  5190. /**
  5191. * Normalize the current Plane in place.
  5192. * Returns the updated Plane.
  5193. */
  5194. Plane.prototype.normalize = function () {
  5195. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5196. var magnitude = 0.0;
  5197. if (norm !== 0) {
  5198. magnitude = 1.0 / norm;
  5199. }
  5200. this.normal.x *= magnitude;
  5201. this.normal.y *= magnitude;
  5202. this.normal.z *= magnitude;
  5203. this.d *= magnitude;
  5204. return this;
  5205. };
  5206. /**
  5207. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5208. */
  5209. Plane.prototype.transform = function (transformation) {
  5210. var transposedMatrix = Matrix.Transpose(transformation);
  5211. var x = this.normal.x;
  5212. var y = this.normal.y;
  5213. var z = this.normal.z;
  5214. var d = this.d;
  5215. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5216. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5217. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5218. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5219. return new Plane(normalX, normalY, normalZ, finalD);
  5220. };
  5221. /**
  5222. * Returns the dot product (float) of the point coordinates and the plane normal.
  5223. */
  5224. Plane.prototype.dotCoordinate = function (point) {
  5225. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5226. };
  5227. /**
  5228. * Updates the current Plane from the plane defined by the three passed points.
  5229. * Returns the updated Plane.
  5230. */
  5231. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5232. var x1 = point2.x - point1.x;
  5233. var y1 = point2.y - point1.y;
  5234. var z1 = point2.z - point1.z;
  5235. var x2 = point3.x - point1.x;
  5236. var y2 = point3.y - point1.y;
  5237. var z2 = point3.z - point1.z;
  5238. var yz = (y1 * z2) - (z1 * y2);
  5239. var xz = (z1 * x2) - (x1 * z2);
  5240. var xy = (x1 * y2) - (y1 * x2);
  5241. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5242. var invPyth;
  5243. if (pyth !== 0) {
  5244. invPyth = 1.0 / pyth;
  5245. }
  5246. else {
  5247. invPyth = 0.0;
  5248. }
  5249. this.normal.x = yz * invPyth;
  5250. this.normal.y = xz * invPyth;
  5251. this.normal.z = xy * invPyth;
  5252. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5253. return this;
  5254. };
  5255. /**
  5256. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5257. */
  5258. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5259. var dot = Vector3.Dot(this.normal, direction);
  5260. return (dot <= epsilon);
  5261. };
  5262. /**
  5263. * Returns the signed distance (float) from the passed point to the Plane.
  5264. */
  5265. Plane.prototype.signedDistanceTo = function (point) {
  5266. return Vector3.Dot(point, this.normal) + this.d;
  5267. };
  5268. // Statics
  5269. /**
  5270. * Returns a new Plane from the passed array.
  5271. */
  5272. Plane.FromArray = function (array) {
  5273. return new Plane(array[0], array[1], array[2], array[3]);
  5274. };
  5275. /**
  5276. * Returns a new Plane defined by the three passed points.
  5277. */
  5278. Plane.FromPoints = function (point1, point2, point3) {
  5279. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5280. result.copyFromPoints(point1, point2, point3);
  5281. return result;
  5282. };
  5283. /**
  5284. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5285. * Note : the vector "normal" is updated because normalized.
  5286. */
  5287. Plane.FromPositionAndNormal = function (origin, normal) {
  5288. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5289. normal.normalize();
  5290. result.normal = normal;
  5291. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5292. return result;
  5293. };
  5294. /**
  5295. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5296. */
  5297. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5298. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5299. return Vector3.Dot(point, normal) + d;
  5300. };
  5301. return Plane;
  5302. }());
  5303. BABYLON.Plane = Plane;
  5304. var Viewport = /** @class */ (function () {
  5305. /**
  5306. * Creates a Viewport object located at (x, y) and sized (width, height).
  5307. */
  5308. function Viewport(x, y, width, height) {
  5309. this.x = x;
  5310. this.y = y;
  5311. this.width = width;
  5312. this.height = height;
  5313. }
  5314. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5315. if (renderWidthOrEngine.getRenderWidth) {
  5316. var engine = renderWidthOrEngine;
  5317. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5318. }
  5319. var renderWidth = renderWidthOrEngine;
  5320. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5321. };
  5322. /**
  5323. * Returns a new Viewport copied from the current one.
  5324. */
  5325. Viewport.prototype.clone = function () {
  5326. return new Viewport(this.x, this.y, this.width, this.height);
  5327. };
  5328. return Viewport;
  5329. }());
  5330. BABYLON.Viewport = Viewport;
  5331. var Frustum = /** @class */ (function () {
  5332. function Frustum() {
  5333. }
  5334. /**
  5335. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5336. */
  5337. Frustum.GetPlanes = function (transform) {
  5338. var frustumPlanes = [];
  5339. for (var index = 0; index < 6; index++) {
  5340. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5341. }
  5342. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5343. return frustumPlanes;
  5344. };
  5345. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5346. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5347. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5348. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5349. frustumPlane.d = transform.m[15] + transform.m[14];
  5350. frustumPlane.normalize();
  5351. };
  5352. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5353. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5354. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5355. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5356. frustumPlane.d = transform.m[15] - transform.m[14];
  5357. frustumPlane.normalize();
  5358. };
  5359. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5363. frustumPlane.d = transform.m[15] + transform.m[12];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5370. frustumPlane.d = transform.m[15] - transform.m[12];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5375. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5376. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5377. frustumPlane.d = transform.m[15] - transform.m[13];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5382. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5383. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5384. frustumPlane.d = transform.m[15] + transform.m[13];
  5385. frustumPlane.normalize();
  5386. };
  5387. /**
  5388. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5389. */
  5390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5391. // Near
  5392. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5393. // Far
  5394. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5395. // Left
  5396. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5397. // Right
  5398. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5399. // Top
  5400. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5401. // Bottom
  5402. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5403. };
  5404. return Frustum;
  5405. }());
  5406. BABYLON.Frustum = Frustum;
  5407. var Space;
  5408. (function (Space) {
  5409. Space[Space["LOCAL"] = 0] = "LOCAL";
  5410. Space[Space["WORLD"] = 1] = "WORLD";
  5411. Space[Space["BONE"] = 2] = "BONE";
  5412. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5413. var Axis = /** @class */ (function () {
  5414. function Axis() {
  5415. }
  5416. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5417. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5418. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5419. return Axis;
  5420. }());
  5421. BABYLON.Axis = Axis;
  5422. ;
  5423. var BezierCurve = /** @class */ (function () {
  5424. function BezierCurve() {
  5425. }
  5426. /**
  5427. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5428. */
  5429. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5430. // Extract X (which is equal to time here)
  5431. var f0 = 1 - 3 * x2 + 3 * x1;
  5432. var f1 = 3 * x2 - 6 * x1;
  5433. var f2 = 3 * x1;
  5434. var refinedT = t;
  5435. for (var i = 0; i < 5; i++) {
  5436. var refinedT2 = refinedT * refinedT;
  5437. var refinedT3 = refinedT2 * refinedT;
  5438. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5439. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5440. refinedT -= (x - t) * slope;
  5441. refinedT = Math.min(1, Math.max(0, refinedT));
  5442. }
  5443. // Resolve cubic bezier for the given x
  5444. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5445. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5446. Math.pow(refinedT, 3);
  5447. };
  5448. return BezierCurve;
  5449. }());
  5450. BABYLON.BezierCurve = BezierCurve;
  5451. var Orientation;
  5452. (function (Orientation) {
  5453. Orientation[Orientation["CW"] = 0] = "CW";
  5454. Orientation[Orientation["CCW"] = 1] = "CCW";
  5455. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5456. var Angle = /** @class */ (function () {
  5457. /**
  5458. * Creates an Angle object of "radians" radians (float).
  5459. */
  5460. function Angle(radians) {
  5461. var _this = this;
  5462. /**
  5463. * Returns the Angle value in degrees (float).
  5464. */
  5465. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5466. /**
  5467. * Returns the Angle value in radians (float).
  5468. */
  5469. this.radians = function () { return _this._radians; };
  5470. this._radians = radians;
  5471. if (this._radians < 0.0)
  5472. this._radians += (2.0 * Math.PI);
  5473. }
  5474. /**
  5475. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5476. */
  5477. Angle.BetweenTwoPoints = function (a, b) {
  5478. var delta = b.subtract(a);
  5479. var theta = Math.atan2(delta.y, delta.x);
  5480. return new Angle(theta);
  5481. };
  5482. /**
  5483. * Returns a new Angle object from the passed float in radians.
  5484. */
  5485. Angle.FromRadians = function (radians) {
  5486. return new Angle(radians);
  5487. };
  5488. /**
  5489. * Returns a new Angle object from the passed float in degrees.
  5490. */
  5491. Angle.FromDegrees = function (degrees) {
  5492. return new Angle(degrees * Math.PI / 180.0);
  5493. };
  5494. return Angle;
  5495. }());
  5496. BABYLON.Angle = Angle;
  5497. var Arc2 = /** @class */ (function () {
  5498. /**
  5499. * Creates an Arc object from the three passed points : start, middle and end.
  5500. */
  5501. function Arc2(startPoint, midPoint, endPoint) {
  5502. this.startPoint = startPoint;
  5503. this.midPoint = midPoint;
  5504. this.endPoint = endPoint;
  5505. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5506. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5507. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5508. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5509. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  5510. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5511. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5512. var a1 = this.startAngle.degrees();
  5513. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5514. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5515. // angles correction
  5516. if (a2 - a1 > +180.0)
  5517. a2 -= 360.0;
  5518. if (a2 - a1 < -180.0)
  5519. a2 += 360.0;
  5520. if (a3 - a2 > +180.0)
  5521. a3 -= 360.0;
  5522. if (a3 - a2 < -180.0)
  5523. a3 += 360.0;
  5524. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5525. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5526. }
  5527. return Arc2;
  5528. }());
  5529. BABYLON.Arc2 = Arc2;
  5530. var Path2 = /** @class */ (function () {
  5531. /**
  5532. * Creates a Path2 object from the starting 2D coordinates x and y.
  5533. */
  5534. function Path2(x, y) {
  5535. this._points = new Array();
  5536. this._length = 0.0;
  5537. this.closed = false;
  5538. this._points.push(new Vector2(x, y));
  5539. }
  5540. /**
  5541. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5542. * Returns the updated Path2.
  5543. */
  5544. Path2.prototype.addLineTo = function (x, y) {
  5545. if (this.closed) {
  5546. //Tools.Error("cannot add lines to closed paths");
  5547. return this;
  5548. }
  5549. var newPoint = new Vector2(x, y);
  5550. var previousPoint = this._points[this._points.length - 1];
  5551. this._points.push(newPoint);
  5552. this._length += newPoint.subtract(previousPoint).length();
  5553. return this;
  5554. };
  5555. /**
  5556. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  5557. * Returns the updated Path2.
  5558. */
  5559. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5560. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5561. if (this.closed) {
  5562. //Tools.Error("cannot add arcs to closed paths");
  5563. return this;
  5564. }
  5565. var startPoint = this._points[this._points.length - 1];
  5566. var midPoint = new Vector2(midX, midY);
  5567. var endPoint = new Vector2(endX, endY);
  5568. var arc = new Arc2(startPoint, midPoint, endPoint);
  5569. var increment = arc.angle.radians() / numberOfSegments;
  5570. if (arc.orientation === Orientation.CW)
  5571. increment *= -1;
  5572. var currentAngle = arc.startAngle.radians() + increment;
  5573. for (var i = 0; i < numberOfSegments; i++) {
  5574. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5575. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5576. this.addLineTo(x, y);
  5577. currentAngle += increment;
  5578. }
  5579. return this;
  5580. };
  5581. /**
  5582. * Closes the Path2.
  5583. * Returns the Path2.
  5584. */
  5585. Path2.prototype.close = function () {
  5586. this.closed = true;
  5587. return this;
  5588. };
  5589. /**
  5590. * Returns the Path2 total length (float).
  5591. */
  5592. Path2.prototype.length = function () {
  5593. var result = this._length;
  5594. if (!this.closed) {
  5595. var lastPoint = this._points[this._points.length - 1];
  5596. var firstPoint = this._points[0];
  5597. result += (firstPoint.subtract(lastPoint).length());
  5598. }
  5599. return result;
  5600. };
  5601. /**
  5602. * Returns the Path2 internal array of points.
  5603. */
  5604. Path2.prototype.getPoints = function () {
  5605. return this._points;
  5606. };
  5607. /**
  5608. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5609. */
  5610. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5611. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5612. //Tools.Error("normalized length position should be between 0 and 1.");
  5613. return Vector2.Zero();
  5614. }
  5615. var lengthPosition = normalizedLengthPosition * this.length();
  5616. var previousOffset = 0;
  5617. for (var i = 0; i < this._points.length; i++) {
  5618. var j = (i + 1) % this._points.length;
  5619. var a = this._points[i];
  5620. var b = this._points[j];
  5621. var bToA = b.subtract(a);
  5622. var nextOffset = (bToA.length() + previousOffset);
  5623. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5624. var dir = bToA.normalize();
  5625. var localOffset = lengthPosition - previousOffset;
  5626. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5627. }
  5628. previousOffset = nextOffset;
  5629. }
  5630. //Tools.Error("internal error");
  5631. return Vector2.Zero();
  5632. };
  5633. /**
  5634. * Returns a new Path2 starting at the coordinates (x, y).
  5635. */
  5636. Path2.StartingAt = function (x, y) {
  5637. return new Path2(x, y);
  5638. };
  5639. return Path2;
  5640. }());
  5641. BABYLON.Path2 = Path2;
  5642. var Path3D = /** @class */ (function () {
  5643. /**
  5644. * new Path3D(path, normal, raw)
  5645. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5646. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5647. * path : an array of Vector3, the curve axis of the Path3D
  5648. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5649. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5650. */
  5651. function Path3D(path, firstNormal, raw) {
  5652. if (firstNormal === void 0) { firstNormal = null; }
  5653. this.path = path;
  5654. this._curve = new Array();
  5655. this._distances = new Array();
  5656. this._tangents = new Array();
  5657. this._normals = new Array();
  5658. this._binormals = new Array();
  5659. for (var p = 0; p < path.length; p++) {
  5660. this._curve[p] = path[p].clone(); // hard copy
  5661. }
  5662. this._raw = raw || false;
  5663. this._compute(firstNormal);
  5664. }
  5665. /**
  5666. * Returns the Path3D array of successive Vector3 designing its curve.
  5667. */
  5668. Path3D.prototype.getCurve = function () {
  5669. return this._curve;
  5670. };
  5671. /**
  5672. * Returns an array populated with tangent vectors on each Path3D curve point.
  5673. */
  5674. Path3D.prototype.getTangents = function () {
  5675. return this._tangents;
  5676. };
  5677. /**
  5678. * Returns an array populated with normal vectors on each Path3D curve point.
  5679. */
  5680. Path3D.prototype.getNormals = function () {
  5681. return this._normals;
  5682. };
  5683. /**
  5684. * Returns an array populated with binormal vectors on each Path3D curve point.
  5685. */
  5686. Path3D.prototype.getBinormals = function () {
  5687. return this._binormals;
  5688. };
  5689. /**
  5690. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5691. */
  5692. Path3D.prototype.getDistances = function () {
  5693. return this._distances;
  5694. };
  5695. /**
  5696. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5697. * Returns the same object updated.
  5698. */
  5699. Path3D.prototype.update = function (path, firstNormal) {
  5700. if (firstNormal === void 0) { firstNormal = null; }
  5701. for (var p = 0; p < path.length; p++) {
  5702. this._curve[p].x = path[p].x;
  5703. this._curve[p].y = path[p].y;
  5704. this._curve[p].z = path[p].z;
  5705. }
  5706. this._compute(firstNormal);
  5707. return this;
  5708. };
  5709. // private function compute() : computes tangents, normals and binormals
  5710. Path3D.prototype._compute = function (firstNormal) {
  5711. var l = this._curve.length;
  5712. // first and last tangents
  5713. this._tangents[0] = this._getFirstNonNullVector(0);
  5714. if (!this._raw) {
  5715. this._tangents[0].normalize();
  5716. }
  5717. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5718. if (!this._raw) {
  5719. this._tangents[l - 1].normalize();
  5720. }
  5721. // normals and binormals at first point : arbitrary vector with _normalVector()
  5722. var tg0 = this._tangents[0];
  5723. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5724. this._normals[0] = pp0;
  5725. if (!this._raw) {
  5726. this._normals[0].normalize();
  5727. }
  5728. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5729. if (!this._raw) {
  5730. this._binormals[0].normalize();
  5731. }
  5732. this._distances[0] = 0.0;
  5733. // normals and binormals : next points
  5734. var prev; // previous vector (segment)
  5735. var cur; // current vector (segment)
  5736. var curTang; // current tangent
  5737. // previous normal
  5738. var prevBinor; // previous binormal
  5739. for (var i = 1; i < l; i++) {
  5740. // tangents
  5741. prev = this._getLastNonNullVector(i);
  5742. if (i < l - 1) {
  5743. cur = this._getFirstNonNullVector(i);
  5744. this._tangents[i] = prev.add(cur);
  5745. this._tangents[i].normalize();
  5746. }
  5747. this._distances[i] = this._distances[i - 1] + prev.length();
  5748. // normals and binormals
  5749. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5750. curTang = this._tangents[i];
  5751. prevBinor = this._binormals[i - 1];
  5752. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5753. if (!this._raw) {
  5754. this._normals[i].normalize();
  5755. }
  5756. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5757. if (!this._raw) {
  5758. this._binormals[i].normalize();
  5759. }
  5760. }
  5761. };
  5762. // private function getFirstNonNullVector(index)
  5763. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5764. Path3D.prototype._getFirstNonNullVector = function (index) {
  5765. var i = 1;
  5766. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5767. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5768. i++;
  5769. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5770. }
  5771. return nNVector;
  5772. };
  5773. // private function getLastNonNullVector(index)
  5774. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5775. Path3D.prototype._getLastNonNullVector = function (index) {
  5776. var i = 1;
  5777. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5778. while (nLVector.length() === 0 && index > i + 1) {
  5779. i++;
  5780. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5781. }
  5782. return nLVector;
  5783. };
  5784. // private function normalVector(v0, vt, va) :
  5785. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5786. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5787. Path3D.prototype._normalVector = function (v0, vt, va) {
  5788. var normal0;
  5789. var tgl = vt.length();
  5790. if (tgl === 0.0) {
  5791. tgl = 1.0;
  5792. }
  5793. if (va === undefined || va === null) {
  5794. var point;
  5795. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5796. point = new Vector3(0.0, -1.0, 0.0);
  5797. }
  5798. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5799. point = new Vector3(1.0, 0.0, 0.0);
  5800. }
  5801. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5802. point = new Vector3(0.0, 0.0, 1.0);
  5803. }
  5804. else {
  5805. point = Vector3.Zero();
  5806. }
  5807. normal0 = Vector3.Cross(vt, point);
  5808. }
  5809. else {
  5810. normal0 = Vector3.Cross(vt, va);
  5811. Vector3.CrossToRef(normal0, vt, normal0);
  5812. }
  5813. normal0.normalize();
  5814. return normal0;
  5815. };
  5816. return Path3D;
  5817. }());
  5818. BABYLON.Path3D = Path3D;
  5819. var Curve3 = /** @class */ (function () {
  5820. /**
  5821. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5822. * A Curve3 is designed from a series of successive Vector3.
  5823. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5824. */
  5825. function Curve3(points) {
  5826. this._length = 0.0;
  5827. this._points = points;
  5828. this._length = this._computeLength(points);
  5829. }
  5830. /**
  5831. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5832. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5833. * @param v1 (Vector3) the control point
  5834. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5835. * @param nbPoints (integer) the wanted number of points in the curve
  5836. */
  5837. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5838. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5839. var bez = new Array();
  5840. var equation = function (t, val0, val1, val2) {
  5841. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5842. return res;
  5843. };
  5844. for (var i = 0; i <= nbPoints; i++) {
  5845. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  5846. }
  5847. return new Curve3(bez);
  5848. };
  5849. /**
  5850. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5851. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5852. * @param v1 (Vector3) the first control point
  5853. * @param v2 (Vector3) the second control point
  5854. * @param v3 (Vector3) the end point of the Cubic Bezier
  5855. * @param nbPoints (integer) the wanted number of points in the curve
  5856. */
  5857. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5858. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5859. var bez = new Array();
  5860. var equation = function (t, val0, val1, val2, val3) {
  5861. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  5862. return res;
  5863. };
  5864. for (var i = 0; i <= nbPoints; i++) {
  5865. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  5866. }
  5867. return new Curve3(bez);
  5868. };
  5869. /**
  5870. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5871. * @param p1 (Vector3) the origin point of the Hermite Spline
  5872. * @param t1 (Vector3) the tangent vector at the origin point
  5873. * @param p2 (Vector3) the end point of the Hermite Spline
  5874. * @param t2 (Vector3) the tangent vector at the end point
  5875. * @param nbPoints (integer) the wanted number of points in the curve
  5876. */
  5877. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5878. var hermite = new Array();
  5879. var step = 1.0 / nbPoints;
  5880. for (var i = 0; i <= nbPoints; i++) {
  5881. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5882. }
  5883. return new Curve3(hermite);
  5884. };
  5885. /**
  5886. * Returns a Curve3 object along a CatmullRom Spline curve :
  5887. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5888. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5889. */
  5890. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5891. var totalPoints = new Array();
  5892. totalPoints.push(points[0].clone());
  5893. Array.prototype.push.apply(totalPoints, points);
  5894. totalPoints.push(points[points.length - 1].clone());
  5895. var catmullRom = new Array();
  5896. var step = 1.0 / nbPoints;
  5897. var amount = 0.0;
  5898. for (var i = 0; i < totalPoints.length - 3; i++) {
  5899. amount = 0;
  5900. for (var c = 0; c < nbPoints; c++) {
  5901. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5902. amount += step;
  5903. }
  5904. }
  5905. i--;
  5906. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5907. return new Curve3(catmullRom);
  5908. };
  5909. /**
  5910. * Returns the Curve3 stored array of successive Vector3
  5911. */
  5912. Curve3.prototype.getPoints = function () {
  5913. return this._points;
  5914. };
  5915. /**
  5916. * Returns the computed length (float) of the curve.
  5917. */
  5918. Curve3.prototype.length = function () {
  5919. return this._length;
  5920. };
  5921. /**
  5922. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5923. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5924. * curveA and curveB keep unchanged.
  5925. */
  5926. Curve3.prototype.continue = function (curve) {
  5927. var lastPoint = this._points[this._points.length - 1];
  5928. var continuedPoints = this._points.slice();
  5929. var curvePoints = curve.getPoints();
  5930. for (var i = 1; i < curvePoints.length; i++) {
  5931. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5932. }
  5933. var continuedCurve = new Curve3(continuedPoints);
  5934. return continuedCurve;
  5935. };
  5936. Curve3.prototype._computeLength = function (path) {
  5937. var l = 0;
  5938. for (var i = 1; i < path.length; i++) {
  5939. l += (path[i].subtract(path[i - 1])).length();
  5940. }
  5941. return l;
  5942. };
  5943. return Curve3;
  5944. }());
  5945. BABYLON.Curve3 = Curve3;
  5946. // Vertex formats
  5947. var PositionNormalVertex = /** @class */ (function () {
  5948. function PositionNormalVertex(position, normal) {
  5949. if (position === void 0) { position = Vector3.Zero(); }
  5950. if (normal === void 0) { normal = Vector3.Up(); }
  5951. this.position = position;
  5952. this.normal = normal;
  5953. }
  5954. PositionNormalVertex.prototype.clone = function () {
  5955. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5956. };
  5957. return PositionNormalVertex;
  5958. }());
  5959. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5960. var PositionNormalTextureVertex = /** @class */ (function () {
  5961. function PositionNormalTextureVertex(position, normal, uv) {
  5962. if (position === void 0) { position = Vector3.Zero(); }
  5963. if (normal === void 0) { normal = Vector3.Up(); }
  5964. if (uv === void 0) { uv = Vector2.Zero(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. this.uv = uv;
  5968. }
  5969. PositionNormalTextureVertex.prototype.clone = function () {
  5970. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5971. };
  5972. return PositionNormalTextureVertex;
  5973. }());
  5974. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5975. // Temporary pre-allocated objects for engine internal use
  5976. // usage in any internal function :
  5977. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5978. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5979. var Tmp = /** @class */ (function () {
  5980. function Tmp() {
  5981. }
  5982. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5983. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5984. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5985. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5986. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5987. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5988. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5989. Matrix.Zero(), Matrix.Zero(),
  5990. Matrix.Zero(), Matrix.Zero(),
  5991. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5992. return Tmp;
  5993. }());
  5994. BABYLON.Tmp = Tmp;
  5995. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5996. var MathTmp = /** @class */ (function () {
  5997. function MathTmp() {
  5998. }
  5999. MathTmp.Vector3 = [Vector3.Zero()];
  6000. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6001. MathTmp.Quaternion = [Quaternion.Zero()];
  6002. return MathTmp;
  6003. }());
  6004. })(BABYLON || (BABYLON = {}));
  6005. //# sourceMappingURL=babylon.math.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var Scalar = /** @class */ (function () {
  6009. function Scalar() {
  6010. }
  6011. /**
  6012. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6013. */
  6014. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6015. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6016. var num = a - b;
  6017. return -epsilon <= num && num <= epsilon;
  6018. };
  6019. /**
  6020. * Returns a string : the upper case translation of the number i to hexadecimal.
  6021. */
  6022. Scalar.ToHex = function (i) {
  6023. var str = i.toString(16);
  6024. if (i <= 15) {
  6025. return ("0" + str).toUpperCase();
  6026. }
  6027. return str.toUpperCase();
  6028. };
  6029. /**
  6030. * Returns -1 if value is negative and +1 is value is positive.
  6031. * Returns the value itself if it's equal to zero.
  6032. */
  6033. Scalar.Sign = function (value) {
  6034. value = +value; // convert to a number
  6035. if (value === 0 || isNaN(value))
  6036. return value;
  6037. return value > 0 ? 1 : -1;
  6038. };
  6039. /**
  6040. * Returns the value itself if it's between min and max.
  6041. * Returns min if the value is lower than min.
  6042. * Returns max if the value is greater than max.
  6043. */
  6044. Scalar.Clamp = function (value, min, max) {
  6045. if (min === void 0) { min = 0; }
  6046. if (max === void 0) { max = 1; }
  6047. return Math.min(max, Math.max(min, value));
  6048. };
  6049. /**
  6050. * Returns the log2 of value.
  6051. */
  6052. Scalar.Log2 = function (value) {
  6053. return Math.log(value) * Math.LOG2E;
  6054. };
  6055. /**
  6056. * Loops the value, so that it is never larger than length and never smaller than 0.
  6057. *
  6058. * This is similar to the modulo operator but it works with floating point numbers.
  6059. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6060. * With t = 5 and length = 2.5, the result would be 0.0.
  6061. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6062. */
  6063. Scalar.Repeat = function (value, length) {
  6064. return value - Math.floor(value / length) * length;
  6065. };
  6066. /**
  6067. * Normalize the value between 0.0 and 1.0 using min and max values
  6068. */
  6069. Scalar.Normalize = function (value, min, max) {
  6070. return (value - min) / (max - min);
  6071. };
  6072. /**
  6073. * Denormalize the value from 0.0 and 1.0 using min and max values
  6074. */
  6075. Scalar.Denormalize = function (normalized, min, max) {
  6076. return (normalized * (max - min) + min);
  6077. };
  6078. /**
  6079. * Calculates the shortest difference between two given angles given in degrees.
  6080. */
  6081. Scalar.DeltaAngle = function (current, target) {
  6082. var num = Scalar.Repeat(target - current, 360.0);
  6083. if (num > 180.0) {
  6084. num -= 360.0;
  6085. }
  6086. return num;
  6087. };
  6088. /**
  6089. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6090. *
  6091. * The returned value will move back and forth between 0 and length
  6092. */
  6093. Scalar.PingPong = function (tx, length) {
  6094. var t = Scalar.Repeat(tx, length * 2.0);
  6095. return length - Math.abs(t - length);
  6096. };
  6097. /**
  6098. * Interpolates between min and max with smoothing at the limits.
  6099. *
  6100. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6101. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6102. */
  6103. Scalar.SmoothStep = function (from, to, tx) {
  6104. var t = Scalar.Clamp(tx);
  6105. t = -2.0 * t * t * t + 3.0 * t * t;
  6106. return to * t + from * (1.0 - t);
  6107. };
  6108. /**
  6109. * Moves a value current towards target.
  6110. *
  6111. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6112. * Negative values of maxDelta pushes the value away from target.
  6113. */
  6114. Scalar.MoveTowards = function (current, target, maxDelta) {
  6115. var result = 0;
  6116. if (Math.abs(target - current) <= maxDelta) {
  6117. result = target;
  6118. }
  6119. else {
  6120. result = current + Scalar.Sign(target - current) * maxDelta;
  6121. }
  6122. return result;
  6123. };
  6124. /**
  6125. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6126. *
  6127. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6128. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6129. */
  6130. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6131. var num = Scalar.DeltaAngle(current, target);
  6132. var result = 0;
  6133. if (-maxDelta < num && num < maxDelta) {
  6134. result = target;
  6135. }
  6136. else {
  6137. target = current + num;
  6138. result = Scalar.MoveTowards(current, target, maxDelta);
  6139. }
  6140. return result;
  6141. };
  6142. /**
  6143. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6144. */
  6145. Scalar.Lerp = function (start, end, amount) {
  6146. return start + ((end - start) * amount);
  6147. };
  6148. /**
  6149. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6150. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6151. */
  6152. Scalar.LerpAngle = function (start, end, amount) {
  6153. var num = Scalar.Repeat(end - start, 360.0);
  6154. if (num > 180.0) {
  6155. num -= 360.0;
  6156. }
  6157. return start + num * Scalar.Clamp(amount);
  6158. };
  6159. /**
  6160. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6161. */
  6162. Scalar.InverseLerp = function (a, b, value) {
  6163. var result = 0;
  6164. if (a != b) {
  6165. result = Scalar.Clamp((value - a) / (b - a));
  6166. }
  6167. else {
  6168. result = 0.0;
  6169. }
  6170. return result;
  6171. };
  6172. /**
  6173. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6174. */
  6175. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6176. var squared = amount * amount;
  6177. var cubed = amount * squared;
  6178. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6179. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6180. var part3 = (cubed - (2.0 * squared)) + amount;
  6181. var part4 = cubed - squared;
  6182. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6183. };
  6184. /**
  6185. * Returns a random float number between and min and max values
  6186. */
  6187. Scalar.RandomRange = function (min, max) {
  6188. if (min === max)
  6189. return min;
  6190. return ((Math.random() * (max - min)) + min);
  6191. };
  6192. /**
  6193. * This function returns percentage of a number in a given range.
  6194. *
  6195. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6196. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6197. */
  6198. Scalar.RangeToPercent = function (number, min, max) {
  6199. return ((number - min) / (max - min));
  6200. };
  6201. /**
  6202. * This function returns number that corresponds to the percentage in a given range.
  6203. *
  6204. * PercentToRange(0.34,0,100) will return 34.
  6205. */
  6206. Scalar.PercentToRange = function (percent, min, max) {
  6207. return ((max - min) * percent + min);
  6208. };
  6209. /**
  6210. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6211. * @param angle The angle to normalize in radian.
  6212. * @return The converted angle.
  6213. */
  6214. Scalar.NormalizeRadians = function (angle) {
  6215. // More precise but slower version kept for reference.
  6216. // angle = angle % Tools.TwoPi;
  6217. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6218. //if (angle > Math.PI) {
  6219. // angle -= Tools.TwoPi;
  6220. //}
  6221. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6222. return angle;
  6223. };
  6224. /**
  6225. * Two pi constants convenient for computation.
  6226. */
  6227. Scalar.TwoPi = Math.PI * 2;
  6228. return Scalar;
  6229. }());
  6230. BABYLON.Scalar = Scalar;
  6231. })(BABYLON || (BABYLON = {}));
  6232. //# sourceMappingURL=babylon.math.scalar.js.map
  6233. //# sourceMappingURL=babylon.mixins.js.map
  6234. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6235. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6236. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6237. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6238. //# sourceMappingURL=babylon.webgl2.js.map
  6239. var BABYLON;
  6240. (function (BABYLON) {
  6241. var __decoratorInitialStore = {};
  6242. var __mergedStore = {};
  6243. var _copySource = function (creationFunction, source, instanciate) {
  6244. var destination = creationFunction();
  6245. // Tags
  6246. if (BABYLON.Tags) {
  6247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6248. }
  6249. var classStore = getMergedStore(destination);
  6250. // Properties
  6251. for (var property in classStore) {
  6252. var propertyDescriptor = classStore[property];
  6253. var sourceProperty = source[property];
  6254. var propertyType = propertyDescriptor.type;
  6255. if (sourceProperty !== undefined && sourceProperty !== null) {
  6256. switch (propertyType) {
  6257. case 0: // Value
  6258. case 6:// Mesh reference
  6259. destination[property] = sourceProperty;
  6260. break;
  6261. case 1:// Texture
  6262. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6263. break;
  6264. case 2: // Color3
  6265. case 3: // FresnelParameters
  6266. case 4: // Vector2
  6267. case 5: // Vector3
  6268. case 7: // Color Curves
  6269. case 10:// Quaternion
  6270. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6271. break;
  6272. }
  6273. }
  6274. }
  6275. return destination;
  6276. };
  6277. function getDirectStore(target) {
  6278. var classKey = target.getClassName();
  6279. if (!__decoratorInitialStore[classKey]) {
  6280. __decoratorInitialStore[classKey] = {};
  6281. }
  6282. return __decoratorInitialStore[classKey];
  6283. }
  6284. /**
  6285. * Return the list of properties flagged as serializable
  6286. * @param target: host object
  6287. */
  6288. function getMergedStore(target) {
  6289. var classKey = target.getClassName();
  6290. if (__mergedStore[classKey]) {
  6291. return __mergedStore[classKey];
  6292. }
  6293. __mergedStore[classKey] = {};
  6294. var store = __mergedStore[classKey];
  6295. var currentTarget = target;
  6296. var currentKey = classKey;
  6297. while (currentKey) {
  6298. var initialStore = __decoratorInitialStore[currentKey];
  6299. for (var property in initialStore) {
  6300. store[property] = initialStore[property];
  6301. }
  6302. var parent_1 = void 0;
  6303. var done = false;
  6304. do {
  6305. parent_1 = Object.getPrototypeOf(currentTarget);
  6306. if (!parent_1.getClassName) {
  6307. done = true;
  6308. break;
  6309. }
  6310. if (parent_1.getClassName() !== currentKey) {
  6311. break;
  6312. }
  6313. currentTarget = parent_1;
  6314. } while (parent_1);
  6315. if (done) {
  6316. break;
  6317. }
  6318. currentKey = parent_1.getClassName();
  6319. currentTarget = parent_1;
  6320. }
  6321. return store;
  6322. }
  6323. function generateSerializableMember(type, sourceName) {
  6324. return function (target, propertyKey) {
  6325. var classStore = getDirectStore(target);
  6326. if (!classStore[propertyKey]) {
  6327. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6328. }
  6329. };
  6330. }
  6331. function generateExpandMember(setCallback, targetKey) {
  6332. if (targetKey === void 0) { targetKey = null; }
  6333. return function (target, propertyKey) {
  6334. var key = targetKey || ("_" + propertyKey);
  6335. Object.defineProperty(target, propertyKey, {
  6336. get: function () {
  6337. return this[key];
  6338. },
  6339. set: function (value) {
  6340. if (this[key] === value) {
  6341. return;
  6342. }
  6343. this[key] = value;
  6344. target[setCallback].apply(this);
  6345. },
  6346. enumerable: true,
  6347. configurable: true
  6348. });
  6349. };
  6350. }
  6351. function expandToProperty(callback, targetKey) {
  6352. if (targetKey === void 0) { targetKey = null; }
  6353. return generateExpandMember(callback, targetKey);
  6354. }
  6355. BABYLON.expandToProperty = expandToProperty;
  6356. function serialize(sourceName) {
  6357. return generateSerializableMember(0, sourceName); // value member
  6358. }
  6359. BABYLON.serialize = serialize;
  6360. function serializeAsTexture(sourceName) {
  6361. return generateSerializableMember(1, sourceName); // texture member
  6362. }
  6363. BABYLON.serializeAsTexture = serializeAsTexture;
  6364. function serializeAsColor3(sourceName) {
  6365. return generateSerializableMember(2, sourceName); // color3 member
  6366. }
  6367. BABYLON.serializeAsColor3 = serializeAsColor3;
  6368. function serializeAsFresnelParameters(sourceName) {
  6369. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6370. }
  6371. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6372. function serializeAsVector2(sourceName) {
  6373. return generateSerializableMember(4, sourceName); // vector2 member
  6374. }
  6375. BABYLON.serializeAsVector2 = serializeAsVector2;
  6376. function serializeAsVector3(sourceName) {
  6377. return generateSerializableMember(5, sourceName); // vector3 member
  6378. }
  6379. BABYLON.serializeAsVector3 = serializeAsVector3;
  6380. function serializeAsMeshReference(sourceName) {
  6381. return generateSerializableMember(6, sourceName); // mesh reference member
  6382. }
  6383. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6384. function serializeAsColorCurves(sourceName) {
  6385. return generateSerializableMember(7, sourceName); // color curves
  6386. }
  6387. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6388. function serializeAsColor4(sourceName) {
  6389. return generateSerializableMember(8, sourceName); // color 4
  6390. }
  6391. BABYLON.serializeAsColor4 = serializeAsColor4;
  6392. function serializeAsImageProcessingConfiguration(sourceName) {
  6393. return generateSerializableMember(9, sourceName); // image processing
  6394. }
  6395. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6396. function serializeAsQuaternion(sourceName) {
  6397. return generateSerializableMember(10, sourceName); // quaternion member
  6398. }
  6399. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6400. var SerializationHelper = /** @class */ (function () {
  6401. function SerializationHelper() {
  6402. }
  6403. SerializationHelper.Serialize = function (entity, serializationObject) {
  6404. if (!serializationObject) {
  6405. serializationObject = {};
  6406. }
  6407. // Tags
  6408. if (BABYLON.Tags) {
  6409. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6410. }
  6411. var serializedProperties = getMergedStore(entity);
  6412. // Properties
  6413. for (var property in serializedProperties) {
  6414. var propertyDescriptor = serializedProperties[property];
  6415. var targetPropertyName = propertyDescriptor.sourceName || property;
  6416. var propertyType = propertyDescriptor.type;
  6417. var sourceProperty = entity[property];
  6418. if (sourceProperty !== undefined && sourceProperty !== null) {
  6419. switch (propertyType) {
  6420. case 0:// Value
  6421. serializationObject[targetPropertyName] = sourceProperty;
  6422. break;
  6423. case 1:// Texture
  6424. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6425. break;
  6426. case 2:// Color3
  6427. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6428. break;
  6429. case 3:// FresnelParameters
  6430. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6431. break;
  6432. case 4:// Vector2
  6433. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6434. break;
  6435. case 5:// Vector3
  6436. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6437. break;
  6438. case 6:// Mesh reference
  6439. serializationObject[targetPropertyName] = sourceProperty.id;
  6440. break;
  6441. case 7:// Color Curves
  6442. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6443. break;
  6444. case 8:// Color 4
  6445. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6446. break;
  6447. case 9:// Image Processing
  6448. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. return serializationObject;
  6454. };
  6455. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6456. if (rootUrl === void 0) { rootUrl = null; }
  6457. var destination = creationFunction();
  6458. if (!rootUrl) {
  6459. rootUrl = "";
  6460. }
  6461. // Tags
  6462. if (BABYLON.Tags) {
  6463. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6464. }
  6465. var classStore = getMergedStore(destination);
  6466. // Properties
  6467. for (var property in classStore) {
  6468. var propertyDescriptor = classStore[property];
  6469. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6470. var propertyType = propertyDescriptor.type;
  6471. if (sourceProperty !== undefined && sourceProperty !== null) {
  6472. var dest = destination;
  6473. switch (propertyType) {
  6474. case 0:// Value
  6475. dest[property] = sourceProperty;
  6476. break;
  6477. case 1:// Texture
  6478. if (scene) {
  6479. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6480. }
  6481. break;
  6482. case 2:// Color3
  6483. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6484. break;
  6485. case 3:// FresnelParameters
  6486. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6487. break;
  6488. case 4:// Vector2
  6489. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6490. break;
  6491. case 5:// Vector3
  6492. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6493. break;
  6494. case 6:// Mesh reference
  6495. if (scene) {
  6496. dest[property] = scene.getLastMeshByID(sourceProperty);
  6497. }
  6498. break;
  6499. case 7:// Color Curves
  6500. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6501. break;
  6502. case 8:// Color 4
  6503. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6504. break;
  6505. case 9:// Image Processing
  6506. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6507. break;
  6508. }
  6509. }
  6510. }
  6511. return destination;
  6512. };
  6513. SerializationHelper.Clone = function (creationFunction, source) {
  6514. return _copySource(creationFunction, source, false);
  6515. };
  6516. SerializationHelper.Instanciate = function (creationFunction, source) {
  6517. return _copySource(creationFunction, source, true);
  6518. };
  6519. return SerializationHelper;
  6520. }());
  6521. BABYLON.SerializationHelper = SerializationHelper;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.decorators.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. /**
  6527. * A class serves as a medium between the observable and its observers
  6528. */
  6529. var EventState = /** @class */ (function () {
  6530. /**
  6531. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6532. */
  6533. function EventState(mask, skipNextObservers, target, currentTarget) {
  6534. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6535. this.initalize(mask, skipNextObservers, target, currentTarget);
  6536. }
  6537. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6538. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6539. this.mask = mask;
  6540. this.skipNextObservers = skipNextObservers;
  6541. this.target = target;
  6542. this.currentTarget = currentTarget;
  6543. return this;
  6544. };
  6545. return EventState;
  6546. }());
  6547. BABYLON.EventState = EventState;
  6548. /**
  6549. * Represent an Observer registered to a given Observable object.
  6550. */
  6551. var Observer = /** @class */ (function () {
  6552. function Observer(callback, mask, scope) {
  6553. if (scope === void 0) { scope = null; }
  6554. this.callback = callback;
  6555. this.mask = mask;
  6556. this.scope = scope;
  6557. }
  6558. return Observer;
  6559. }());
  6560. BABYLON.Observer = Observer;
  6561. /**
  6562. * Represent a list of observers registered to multiple Observables object.
  6563. */
  6564. var MultiObserver = /** @class */ (function () {
  6565. function MultiObserver() {
  6566. }
  6567. MultiObserver.prototype.dispose = function () {
  6568. if (this._observers && this._observables) {
  6569. for (var index = 0; index < this._observers.length; index++) {
  6570. this._observables[index].remove(this._observers[index]);
  6571. }
  6572. }
  6573. this._observers = null;
  6574. this._observables = null;
  6575. };
  6576. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6577. if (mask === void 0) { mask = -1; }
  6578. if (scope === void 0) { scope = null; }
  6579. var result = new MultiObserver();
  6580. result._observers = new Array();
  6581. result._observables = observables;
  6582. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6583. var observable = observables_1[_i];
  6584. var observer = observable.add(callback, mask, false, scope);
  6585. if (observer) {
  6586. result._observers.push(observer);
  6587. }
  6588. }
  6589. return result;
  6590. };
  6591. return MultiObserver;
  6592. }());
  6593. BABYLON.MultiObserver = MultiObserver;
  6594. /**
  6595. * The Observable class is a simple implementation of the Observable pattern.
  6596. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  6597. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6598. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  6599. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  6600. */
  6601. var Observable = /** @class */ (function () {
  6602. function Observable(onObserverAdded) {
  6603. this._observers = new Array();
  6604. this._eventState = new EventState(0);
  6605. if (onObserverAdded) {
  6606. this._onObserverAdded = onObserverAdded;
  6607. }
  6608. }
  6609. /**
  6610. * Create a new Observer with the specified callback
  6611. * @param callback the callback that will be executed for that Observer
  6612. * @param mask the mask used to filter observers
  6613. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  6614. * @param scope optional scope for the callback to be called from
  6615. */
  6616. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6617. if (mask === void 0) { mask = -1; }
  6618. if (insertFirst === void 0) { insertFirst = false; }
  6619. if (scope === void 0) { scope = null; }
  6620. if (!callback) {
  6621. return null;
  6622. }
  6623. var observer = new Observer(callback, mask, scope);
  6624. if (insertFirst) {
  6625. this._observers.unshift(observer);
  6626. }
  6627. else {
  6628. this._observers.push(observer);
  6629. }
  6630. if (this._onObserverAdded) {
  6631. this._onObserverAdded(observer);
  6632. }
  6633. return observer;
  6634. };
  6635. /**
  6636. * Remove an Observer from the Observable object
  6637. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6638. */
  6639. Observable.prototype.remove = function (observer) {
  6640. if (!observer) {
  6641. return false;
  6642. }
  6643. var index = this._observers.indexOf(observer);
  6644. if (index !== -1) {
  6645. this._observers.splice(index, 1);
  6646. return true;
  6647. }
  6648. return false;
  6649. };
  6650. /**
  6651. * Remove a callback from the Observable object
  6652. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6653. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6654. */
  6655. Observable.prototype.removeCallback = function (callback, scope) {
  6656. for (var index = 0; index < this._observers.length; index++) {
  6657. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6658. this._observers.splice(index, 1);
  6659. return true;
  6660. }
  6661. }
  6662. return false;
  6663. };
  6664. /**
  6665. * Notify all Observers by calling their respective callback with the given data
  6666. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6667. * @param eventData
  6668. * @param mask
  6669. */
  6670. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6671. if (mask === void 0) { mask = -1; }
  6672. if (!this._observers.length) {
  6673. return true;
  6674. }
  6675. var state = this._eventState;
  6676. state.mask = mask;
  6677. state.target = target;
  6678. state.currentTarget = currentTarget;
  6679. state.skipNextObservers = false;
  6680. state.lastReturnValue = eventData;
  6681. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6682. var obs = _a[_i];
  6683. if (obs.mask & mask) {
  6684. if (obs.scope) {
  6685. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6686. }
  6687. else {
  6688. state.lastReturnValue = obs.callback(eventData, state);
  6689. }
  6690. }
  6691. if (state.skipNextObservers) {
  6692. return false;
  6693. }
  6694. }
  6695. return true;
  6696. };
  6697. /**
  6698. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6699. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6700. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6701. * and it is crucial that all callbacks will be executed.
  6702. * The order of the callbacks is kept, callbacks are not executed parallel.
  6703. *
  6704. * @param eventData The data to be sent to each callback
  6705. * @param mask is used to filter observers defaults to -1
  6706. * @param target the callback target (see EventState)
  6707. * @param currentTarget The current object in the bubbling phase
  6708. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6709. */
  6710. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6711. if (mask === void 0) { mask = -1; }
  6712. // create an empty promise
  6713. var p = Promise.resolve(eventData);
  6714. // no observers? return this promise.
  6715. if (!this._observers.length) {
  6716. return p;
  6717. }
  6718. var state = this._eventState;
  6719. state.mask = mask;
  6720. state.target = target;
  6721. state.currentTarget = currentTarget;
  6722. state.skipNextObservers = false;
  6723. // execute one callback after another (not using Promise.all, the order is important)
  6724. this._observers.forEach(function (obs) {
  6725. if (state.skipNextObservers) {
  6726. return;
  6727. }
  6728. if (obs.mask & mask) {
  6729. if (obs.scope) {
  6730. p = p.then(function (lastReturnedValue) {
  6731. state.lastReturnValue = lastReturnedValue;
  6732. return obs.callback.apply(obs.scope, [eventData, state]);
  6733. });
  6734. }
  6735. else {
  6736. p = p.then(function (lastReturnedValue) {
  6737. state.lastReturnValue = lastReturnedValue;
  6738. return obs.callback(eventData, state);
  6739. });
  6740. }
  6741. }
  6742. });
  6743. // return the eventData
  6744. return p.then(function () { return eventData; });
  6745. };
  6746. /**
  6747. * Notify a specific observer
  6748. * @param eventData
  6749. * @param mask
  6750. */
  6751. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6752. if (mask === void 0) { mask = -1; }
  6753. var state = this._eventState;
  6754. state.mask = mask;
  6755. state.skipNextObservers = false;
  6756. observer.callback(eventData, state);
  6757. };
  6758. /**
  6759. * return true is the Observable has at least one Observer registered
  6760. */
  6761. Observable.prototype.hasObservers = function () {
  6762. return this._observers.length > 0;
  6763. };
  6764. /**
  6765. * Clear the list of observers
  6766. */
  6767. Observable.prototype.clear = function () {
  6768. this._observers = new Array();
  6769. this._onObserverAdded = null;
  6770. };
  6771. /**
  6772. * Clone the current observable
  6773. */
  6774. Observable.prototype.clone = function () {
  6775. var result = new Observable();
  6776. result._observers = this._observers.slice(0);
  6777. return result;
  6778. };
  6779. /**
  6780. * Does this observable handles observer registered with a given mask
  6781. * @param {number} trigger - the mask to be tested
  6782. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6783. **/
  6784. Observable.prototype.hasSpecificMask = function (mask) {
  6785. if (mask === void 0) { mask = -1; }
  6786. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6787. var obs = _a[_i];
  6788. if (obs.mask & mask || obs.mask === mask) {
  6789. return true;
  6790. }
  6791. }
  6792. return false;
  6793. };
  6794. return Observable;
  6795. }());
  6796. BABYLON.Observable = Observable;
  6797. })(BABYLON || (BABYLON = {}));
  6798. //# sourceMappingURL=babylon.observable.js.map
  6799. var BABYLON;
  6800. (function (BABYLON) {
  6801. var SmartArray = /** @class */ (function () {
  6802. function SmartArray(capacity) {
  6803. this.length = 0;
  6804. this.data = new Array(capacity);
  6805. this._id = SmartArray._GlobalId++;
  6806. }
  6807. SmartArray.prototype.push = function (value) {
  6808. this.data[this.length++] = value;
  6809. if (this.length > this.data.length) {
  6810. this.data.length *= 2;
  6811. }
  6812. };
  6813. SmartArray.prototype.forEach = function (func) {
  6814. for (var index = 0; index < this.length; index++) {
  6815. func(this.data[index]);
  6816. }
  6817. };
  6818. SmartArray.prototype.sort = function (compareFn) {
  6819. this.data.sort(compareFn);
  6820. };
  6821. SmartArray.prototype.reset = function () {
  6822. this.length = 0;
  6823. };
  6824. SmartArray.prototype.dispose = function () {
  6825. this.reset();
  6826. if (this.data) {
  6827. this.data.length = 0;
  6828. this.data = [];
  6829. }
  6830. };
  6831. SmartArray.prototype.concat = function (array) {
  6832. if (array.length === 0) {
  6833. return;
  6834. }
  6835. if (this.length + array.length > this.data.length) {
  6836. this.data.length = (this.length + array.length) * 2;
  6837. }
  6838. for (var index = 0; index < array.length; index++) {
  6839. this.data[this.length++] = (array.data || array)[index];
  6840. }
  6841. };
  6842. SmartArray.prototype.indexOf = function (value) {
  6843. var position = this.data.indexOf(value);
  6844. if (position >= this.length) {
  6845. return -1;
  6846. }
  6847. return position;
  6848. };
  6849. SmartArray.prototype.contains = function (value) {
  6850. return this.data.indexOf(value) !== -1;
  6851. };
  6852. // Statics
  6853. SmartArray._GlobalId = 0;
  6854. return SmartArray;
  6855. }());
  6856. BABYLON.SmartArray = SmartArray;
  6857. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6858. __extends(SmartArrayNoDuplicate, _super);
  6859. function SmartArrayNoDuplicate() {
  6860. var _this = _super !== null && _super.apply(this, arguments) || this;
  6861. _this._duplicateId = 0;
  6862. return _this;
  6863. }
  6864. SmartArrayNoDuplicate.prototype.push = function (value) {
  6865. _super.prototype.push.call(this, value);
  6866. if (!value.__smartArrayFlags) {
  6867. value.__smartArrayFlags = {};
  6868. }
  6869. value.__smartArrayFlags[this._id] = this._duplicateId;
  6870. };
  6871. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6872. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6873. return false;
  6874. }
  6875. this.push(value);
  6876. return true;
  6877. };
  6878. SmartArrayNoDuplicate.prototype.reset = function () {
  6879. _super.prototype.reset.call(this);
  6880. this._duplicateId++;
  6881. };
  6882. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6883. if (array.length === 0) {
  6884. return;
  6885. }
  6886. if (this.length + array.length > this.data.length) {
  6887. this.data.length = (this.length + array.length) * 2;
  6888. }
  6889. for (var index = 0; index < array.length; index++) {
  6890. var item = (array.data || array)[index];
  6891. this.pushNoDuplicate(item);
  6892. }
  6893. };
  6894. return SmartArrayNoDuplicate;
  6895. }(SmartArray));
  6896. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6897. })(BABYLON || (BABYLON = {}));
  6898. //# sourceMappingURL=babylon.smartArray.js.map
  6899. var BABYLON;
  6900. (function (BABYLON) {
  6901. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6902. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6903. var LoadFileError = /** @class */ (function (_super) {
  6904. __extends(LoadFileError, _super);
  6905. function LoadFileError(message, request) {
  6906. var _this = _super.call(this, message) || this;
  6907. _this.request = request;
  6908. _this.name = "LoadFileError";
  6909. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6910. return _this;
  6911. }
  6912. // Polyfill for Object.setPrototypeOf if necessary.
  6913. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6914. return LoadFileError;
  6915. }(Error));
  6916. BABYLON.LoadFileError = LoadFileError;
  6917. var RetryStrategy = /** @class */ (function () {
  6918. function RetryStrategy() {
  6919. }
  6920. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6921. if (maxRetries === void 0) { maxRetries = 3; }
  6922. if (baseInterval === void 0) { baseInterval = 500; }
  6923. return function (url, request, retryIndex) {
  6924. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6925. return -1;
  6926. }
  6927. return Math.pow(2, retryIndex) * baseInterval;
  6928. };
  6929. };
  6930. return RetryStrategy;
  6931. }());
  6932. BABYLON.RetryStrategy = RetryStrategy;
  6933. // Screenshots
  6934. var screenshotCanvas;
  6935. var cloneValue = function (source, destinationObject) {
  6936. if (!source)
  6937. return null;
  6938. if (source instanceof BABYLON.Mesh) {
  6939. return null;
  6940. }
  6941. if (source instanceof BABYLON.SubMesh) {
  6942. return source.clone(destinationObject);
  6943. }
  6944. else if (source.clone) {
  6945. return source.clone();
  6946. }
  6947. return null;
  6948. };
  6949. var Tools = /** @class */ (function () {
  6950. function Tools() {
  6951. }
  6952. /**
  6953. * Interpolates between a and b via alpha
  6954. * @param a The lower value (returned when alpha = 0)
  6955. * @param b The upper value (returned when alpha = 1)
  6956. * @param alpha The interpolation-factor
  6957. * @return The mixed value
  6958. */
  6959. Tools.Mix = function (a, b, alpha) {
  6960. return a * (1 - alpha) + b * alpha;
  6961. };
  6962. Tools.Instantiate = function (className) {
  6963. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6964. return Tools.RegisteredExternalClasses[className];
  6965. }
  6966. var arr = className.split(".");
  6967. var fn = (window || this);
  6968. for (var i = 0, len = arr.length; i < len; i++) {
  6969. fn = fn[arr[i]];
  6970. }
  6971. if (typeof fn !== "function") {
  6972. return null;
  6973. }
  6974. return fn;
  6975. };
  6976. /**
  6977. * Provides a slice function that will work even on IE
  6978. * @param data defines the array to slice
  6979. * @returns the new sliced array
  6980. */
  6981. Tools.Slice = function (data) {
  6982. if (data.slice) {
  6983. return data.slice();
  6984. }
  6985. return Array.prototype.slice.call(data);
  6986. };
  6987. Tools.SetImmediate = function (action) {
  6988. if (window.setImmediate) {
  6989. window.setImmediate(action);
  6990. }
  6991. else {
  6992. setTimeout(action, 1);
  6993. }
  6994. };
  6995. Tools.IsExponentOfTwo = function (value) {
  6996. var count = 1;
  6997. do {
  6998. count *= 2;
  6999. } while (count < value);
  7000. return count === value;
  7001. };
  7002. /**
  7003. * Find the next highest power of two.
  7004. * @param x Number to start search from.
  7005. * @return Next highest power of two.
  7006. */
  7007. Tools.CeilingPOT = function (x) {
  7008. x--;
  7009. x |= x >> 1;
  7010. x |= x >> 2;
  7011. x |= x >> 4;
  7012. x |= x >> 8;
  7013. x |= x >> 16;
  7014. x++;
  7015. return x;
  7016. };
  7017. /**
  7018. * Find the next lowest power of two.
  7019. * @param x Number to start search from.
  7020. * @return Next lowest power of two.
  7021. */
  7022. Tools.FloorPOT = function (x) {
  7023. x = x | (x >> 1);
  7024. x = x | (x >> 2);
  7025. x = x | (x >> 4);
  7026. x = x | (x >> 8);
  7027. x = x | (x >> 16);
  7028. return x - (x >> 1);
  7029. };
  7030. /**
  7031. * Find the nearest power of two.
  7032. * @param x Number to start search from.
  7033. * @return Next nearest power of two.
  7034. */
  7035. Tools.NearestPOT = function (x) {
  7036. var c = Tools.CeilingPOT(x);
  7037. var f = Tools.FloorPOT(x);
  7038. return (c - x) > (x - f) ? f : c;
  7039. };
  7040. Tools.GetExponentOfTwo = function (value, max, mode) {
  7041. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7042. var pot;
  7043. switch (mode) {
  7044. case BABYLON.Engine.SCALEMODE_FLOOR:
  7045. pot = Tools.FloorPOT(value);
  7046. break;
  7047. case BABYLON.Engine.SCALEMODE_NEAREST:
  7048. pot = Tools.NearestPOT(value);
  7049. break;
  7050. case BABYLON.Engine.SCALEMODE_CEILING:
  7051. default:
  7052. pot = Tools.CeilingPOT(value);
  7053. break;
  7054. }
  7055. return Math.min(pot, max);
  7056. };
  7057. Tools.GetFilename = function (path) {
  7058. var index = path.lastIndexOf("/");
  7059. if (index < 0)
  7060. return path;
  7061. return path.substring(index + 1);
  7062. };
  7063. Tools.GetFolderPath = function (uri) {
  7064. var index = uri.lastIndexOf("/");
  7065. if (index < 0)
  7066. return "";
  7067. return uri.substring(0, index + 1);
  7068. };
  7069. Tools.GetDOMTextContent = function (element) {
  7070. var result = "";
  7071. var child = element.firstChild;
  7072. while (child) {
  7073. if (child.nodeType === 3) {
  7074. result += child.textContent;
  7075. }
  7076. child = child.nextSibling;
  7077. }
  7078. return result;
  7079. };
  7080. Tools.ToDegrees = function (angle) {
  7081. return angle * 180 / Math.PI;
  7082. };
  7083. Tools.ToRadians = function (angle) {
  7084. return angle * Math.PI / 180;
  7085. };
  7086. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7087. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7088. var output = "";
  7089. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7090. var i = 0;
  7091. var bytes = new Uint8Array(buffer);
  7092. while (i < bytes.length) {
  7093. chr1 = bytes[i++];
  7094. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7095. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7096. enc1 = chr1 >> 2;
  7097. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7098. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7099. enc4 = chr3 & 63;
  7100. if (isNaN(chr2)) {
  7101. enc3 = enc4 = 64;
  7102. }
  7103. else if (isNaN(chr3)) {
  7104. enc4 = 64;
  7105. }
  7106. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7107. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7108. }
  7109. return "data:image/png;base64," + output;
  7110. };
  7111. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7112. if (bias === void 0) { bias = null; }
  7113. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7114. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7115. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7116. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7117. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7118. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7119. }
  7120. if (bias) {
  7121. minimum.x -= minimum.x * bias.x + bias.y;
  7122. minimum.y -= minimum.y * bias.x + bias.y;
  7123. minimum.z -= minimum.z * bias.x + bias.y;
  7124. maximum.x += maximum.x * bias.x + bias.y;
  7125. maximum.y += maximum.y * bias.x + bias.y;
  7126. maximum.z += maximum.z * bias.x + bias.y;
  7127. }
  7128. return {
  7129. minimum: minimum,
  7130. maximum: maximum
  7131. };
  7132. };
  7133. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7134. if (bias === void 0) { bias = null; }
  7135. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7136. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7137. if (!stride) {
  7138. stride = 3;
  7139. }
  7140. for (var index = start; index < start + count; index++) {
  7141. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7142. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7143. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7144. }
  7145. if (bias) {
  7146. minimum.x -= minimum.x * bias.x + bias.y;
  7147. minimum.y -= minimum.y * bias.x + bias.y;
  7148. minimum.z -= minimum.z * bias.x + bias.y;
  7149. maximum.x += maximum.x * bias.x + bias.y;
  7150. maximum.y += maximum.y * bias.x + bias.y;
  7151. maximum.z += maximum.z * bias.x + bias.y;
  7152. }
  7153. return {
  7154. minimum: minimum,
  7155. maximum: maximum
  7156. };
  7157. };
  7158. Tools.Vector2ArrayFeeder = function (array) {
  7159. return function (index) {
  7160. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7161. var length = isFloatArray ? array.length / 2 : array.length;
  7162. if (index >= length) {
  7163. return null;
  7164. }
  7165. if (isFloatArray) {
  7166. var fa = array;
  7167. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7168. }
  7169. var a = array;
  7170. return a[index];
  7171. };
  7172. };
  7173. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7174. if (bias === void 0) { bias = null; }
  7175. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7176. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7177. var i = 0;
  7178. var cur = feeder(i++);
  7179. while (cur) {
  7180. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7181. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7182. cur = feeder(i++);
  7183. }
  7184. if (bias) {
  7185. minimum.x -= minimum.x * bias.x + bias.y;
  7186. minimum.y -= minimum.y * bias.x + bias.y;
  7187. maximum.x += maximum.x * bias.x + bias.y;
  7188. maximum.y += maximum.y * bias.x + bias.y;
  7189. }
  7190. return {
  7191. minimum: minimum,
  7192. maximum: maximum
  7193. };
  7194. };
  7195. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7196. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7197. return null;
  7198. return Array.isArray(obj) ? obj : [obj];
  7199. };
  7200. // Misc.
  7201. Tools.GetPointerPrefix = function () {
  7202. var eventPrefix = "pointer";
  7203. // Check if pointer events are supported
  7204. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7205. eventPrefix = "mouse";
  7206. }
  7207. return eventPrefix;
  7208. };
  7209. /**
  7210. * @param func - the function to be called
  7211. * @param requester - the object that will request the next frame. Falls back to window.
  7212. */
  7213. Tools.QueueNewFrame = function (func, requester) {
  7214. if (!Tools.IsWindowObjectExist()) {
  7215. return setTimeout(func, 16);
  7216. }
  7217. if (!requester) {
  7218. requester = window;
  7219. }
  7220. if (requester.requestAnimationFrame) {
  7221. return requester.requestAnimationFrame(func);
  7222. }
  7223. else if (requester.msRequestAnimationFrame) {
  7224. return requester.msRequestAnimationFrame(func);
  7225. }
  7226. else if (requester.webkitRequestAnimationFrame) {
  7227. return requester.webkitRequestAnimationFrame(func);
  7228. }
  7229. else if (requester.mozRequestAnimationFrame) {
  7230. return requester.mozRequestAnimationFrame(func);
  7231. }
  7232. else if (requester.oRequestAnimationFrame) {
  7233. return requester.oRequestAnimationFrame(func);
  7234. }
  7235. else {
  7236. return window.setTimeout(func, 16);
  7237. }
  7238. };
  7239. Tools.RequestFullscreen = function (element) {
  7240. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7241. if (!requestFunction)
  7242. return;
  7243. requestFunction.call(element);
  7244. };
  7245. Tools.ExitFullscreen = function () {
  7246. if (document.exitFullscreen) {
  7247. document.exitFullscreen();
  7248. }
  7249. else if (document.mozCancelFullScreen) {
  7250. document.mozCancelFullScreen();
  7251. }
  7252. else if (document.webkitCancelFullScreen) {
  7253. document.webkitCancelFullScreen();
  7254. }
  7255. else if (document.msCancelFullScreen) {
  7256. document.msCancelFullScreen();
  7257. }
  7258. };
  7259. Tools.SetCorsBehavior = function (url, element) {
  7260. if (url && url.indexOf("data:") === 0) {
  7261. return;
  7262. }
  7263. if (Tools.CorsBehavior) {
  7264. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7265. element.crossOrigin = Tools.CorsBehavior;
  7266. }
  7267. else {
  7268. var result = Tools.CorsBehavior(url);
  7269. if (result) {
  7270. element.crossOrigin = result;
  7271. }
  7272. }
  7273. }
  7274. };
  7275. // External files
  7276. Tools.CleanUrl = function (url) {
  7277. url = url.replace(/#/mg, "%23");
  7278. return url;
  7279. };
  7280. Tools.LoadImage = function (url, onLoad, onError, database) {
  7281. if (url instanceof ArrayBuffer) {
  7282. url = Tools.EncodeArrayBufferTobase64(url);
  7283. }
  7284. url = Tools.CleanUrl(url);
  7285. url = Tools.PreprocessUrl(url);
  7286. var img = new Image();
  7287. Tools.SetCorsBehavior(url, img);
  7288. img.onload = function () {
  7289. onLoad(img);
  7290. };
  7291. img.onerror = function (err) {
  7292. Tools.Error("Error while trying to load image: " + url);
  7293. if (onError) {
  7294. onError("Error while trying to load image: " + url, err);
  7295. }
  7296. };
  7297. var noIndexedDB = function () {
  7298. img.src = url;
  7299. };
  7300. var loadFromIndexedDB = function () {
  7301. if (database) {
  7302. database.loadImageFromDB(url, img);
  7303. }
  7304. };
  7305. //ANY database to do!
  7306. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7307. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7308. }
  7309. else {
  7310. if (url.indexOf("file:") !== -1) {
  7311. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7312. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7313. try {
  7314. var blobURL;
  7315. try {
  7316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7317. }
  7318. catch (ex) {
  7319. // Chrome doesn't support oneTimeOnly parameter
  7320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7321. }
  7322. img.src = blobURL;
  7323. }
  7324. catch (e) {
  7325. img.src = "";
  7326. }
  7327. return img;
  7328. }
  7329. }
  7330. noIndexedDB();
  7331. }
  7332. return img;
  7333. };
  7334. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7335. url = Tools.CleanUrl(url);
  7336. url = Tools.PreprocessUrl(url);
  7337. // If file and file input are set
  7338. if (url.indexOf("file:") !== -1) {
  7339. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7340. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7341. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7342. }
  7343. }
  7344. var loadUrl = Tools.BaseUrl + url;
  7345. var aborted = false;
  7346. var fileRequest = {
  7347. onCompleteObservable: new BABYLON.Observable(),
  7348. abort: function () { return aborted = true; },
  7349. };
  7350. var requestFile = function () {
  7351. var request = new XMLHttpRequest();
  7352. var retryHandle = null;
  7353. fileRequest.abort = function () {
  7354. aborted = true;
  7355. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7356. request.abort();
  7357. }
  7358. if (retryHandle !== null) {
  7359. clearTimeout(retryHandle);
  7360. retryHandle = null;
  7361. }
  7362. };
  7363. var retryLoop = function (retryIndex) {
  7364. request.open('GET', loadUrl, true);
  7365. if (useArrayBuffer) {
  7366. request.responseType = "arraybuffer";
  7367. }
  7368. if (onProgress) {
  7369. request.addEventListener("progress", onProgress);
  7370. }
  7371. var onLoadEnd = function () {
  7372. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7373. };
  7374. request.addEventListener("loadend", onLoadEnd);
  7375. var onReadyStateChange = function () {
  7376. if (aborted) {
  7377. return;
  7378. }
  7379. // In case of undefined state in some browsers.
  7380. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7381. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7382. request.removeEventListener("readystatechange", onReadyStateChange);
  7383. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7384. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7385. return;
  7386. }
  7387. var retryStrategy = Tools.DefaultRetryStrategy;
  7388. if (retryStrategy) {
  7389. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7390. if (waitTime !== -1) {
  7391. // Prevent the request from completing for retry.
  7392. request.removeEventListener("loadend", onLoadEnd);
  7393. request = new XMLHttpRequest();
  7394. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7395. return;
  7396. }
  7397. }
  7398. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7399. if (onError) {
  7400. onError(request, e);
  7401. }
  7402. else {
  7403. throw e;
  7404. }
  7405. }
  7406. };
  7407. request.addEventListener("readystatechange", onReadyStateChange);
  7408. request.send();
  7409. };
  7410. retryLoop(0);
  7411. };
  7412. // Caching all files
  7413. if (database && database.enableSceneOffline) {
  7414. var noIndexedDB_1 = function () {
  7415. if (!aborted) {
  7416. requestFile();
  7417. }
  7418. };
  7419. var loadFromIndexedDB = function () {
  7420. // TODO: database needs to support aborting and should return a IFileRequest
  7421. if (aborted) {
  7422. return;
  7423. }
  7424. if (database) {
  7425. database.loadFileFromDB(url, function (data) {
  7426. if (!aborted) {
  7427. onSuccess(data);
  7428. }
  7429. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7430. }, onProgress ? function (event) {
  7431. if (!aborted) {
  7432. onProgress(event);
  7433. }
  7434. } : undefined, noIndexedDB_1, useArrayBuffer);
  7435. }
  7436. };
  7437. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7438. }
  7439. else {
  7440. requestFile();
  7441. }
  7442. return fileRequest;
  7443. };
  7444. /**
  7445. * Load a script (identified by an url). When the url returns, the
  7446. * content of this file is added into a new script element, attached to the DOM (body element)
  7447. */
  7448. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7449. var head = document.getElementsByTagName('head')[0];
  7450. var script = document.createElement('script');
  7451. script.type = 'text/javascript';
  7452. script.src = scriptUrl;
  7453. script.onload = function () {
  7454. if (onSuccess) {
  7455. onSuccess();
  7456. }
  7457. };
  7458. script.onerror = function (e) {
  7459. if (onError) {
  7460. onError("Unable to load script", e);
  7461. }
  7462. };
  7463. head.appendChild(script);
  7464. };
  7465. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7466. var reader = new FileReader();
  7467. var request = {
  7468. onCompleteObservable: new BABYLON.Observable(),
  7469. abort: function () { return reader.abort(); },
  7470. };
  7471. reader.onloadend = function (e) {
  7472. request.onCompleteObservable.notifyObservers(request);
  7473. };
  7474. reader.onload = function (e) {
  7475. //target doesn't have result from ts 1.3
  7476. callback(e.target['result']);
  7477. };
  7478. reader.onprogress = progressCallback;
  7479. reader.readAsDataURL(fileToLoad);
  7480. return request;
  7481. };
  7482. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7483. var reader = new FileReader();
  7484. var request = {
  7485. onCompleteObservable: new BABYLON.Observable(),
  7486. abort: function () { return reader.abort(); },
  7487. };
  7488. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7489. reader.onerror = function (e) {
  7490. Tools.Log("Error while reading file: " + fileToLoad.name);
  7491. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7492. };
  7493. reader.onload = function (e) {
  7494. //target doesn't have result from ts 1.3
  7495. callback(e.target['result']);
  7496. };
  7497. if (progressCallBack) {
  7498. reader.onprogress = progressCallBack;
  7499. }
  7500. if (!useArrayBuffer) {
  7501. // Asynchronous read
  7502. reader.readAsText(fileToLoad);
  7503. }
  7504. else {
  7505. reader.readAsArrayBuffer(fileToLoad);
  7506. }
  7507. return request;
  7508. };
  7509. //returns a downloadable url to a file content.
  7510. Tools.FileAsURL = function (content) {
  7511. var fileBlob = new Blob([content]);
  7512. var url = window.URL || window.webkitURL;
  7513. var link = url.createObjectURL(fileBlob);
  7514. return link;
  7515. };
  7516. // Misc.
  7517. Tools.Format = function (value, decimals) {
  7518. if (decimals === void 0) { decimals = 2; }
  7519. return value.toFixed(decimals);
  7520. };
  7521. Tools.CheckExtends = function (v, min, max) {
  7522. if (v.x < min.x)
  7523. min.x = v.x;
  7524. if (v.y < min.y)
  7525. min.y = v.y;
  7526. if (v.z < min.z)
  7527. min.z = v.z;
  7528. if (v.x > max.x)
  7529. max.x = v.x;
  7530. if (v.y > max.y)
  7531. max.y = v.y;
  7532. if (v.z > max.z)
  7533. max.z = v.z;
  7534. };
  7535. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7536. for (var prop in source) {
  7537. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7538. continue;
  7539. }
  7540. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7541. continue;
  7542. }
  7543. var sourceValue = source[prop];
  7544. var typeOfSourceValue = typeof sourceValue;
  7545. if (typeOfSourceValue === "function") {
  7546. continue;
  7547. }
  7548. if (typeOfSourceValue === "object") {
  7549. if (sourceValue instanceof Array) {
  7550. destination[prop] = [];
  7551. if (sourceValue.length > 0) {
  7552. if (typeof sourceValue[0] == "object") {
  7553. for (var index = 0; index < sourceValue.length; index++) {
  7554. var clonedValue = cloneValue(sourceValue[index], destination);
  7555. if (destination[prop].indexOf(clonedValue) === -1) {
  7556. destination[prop].push(clonedValue);
  7557. }
  7558. }
  7559. }
  7560. else {
  7561. destination[prop] = sourceValue.slice(0);
  7562. }
  7563. }
  7564. }
  7565. else {
  7566. destination[prop] = cloneValue(sourceValue, destination);
  7567. }
  7568. }
  7569. else {
  7570. destination[prop] = sourceValue;
  7571. }
  7572. }
  7573. };
  7574. Tools.IsEmpty = function (obj) {
  7575. for (var i in obj) {
  7576. if (obj.hasOwnProperty(i)) {
  7577. return false;
  7578. }
  7579. }
  7580. return true;
  7581. };
  7582. Tools.RegisterTopRootEvents = function (events) {
  7583. for (var index = 0; index < events.length; index++) {
  7584. var event = events[index];
  7585. window.addEventListener(event.name, event.handler, false);
  7586. try {
  7587. if (window.parent) {
  7588. window.parent.addEventListener(event.name, event.handler, false);
  7589. }
  7590. }
  7591. catch (e) {
  7592. // Silently fails...
  7593. }
  7594. }
  7595. };
  7596. Tools.UnregisterTopRootEvents = function (events) {
  7597. for (var index = 0; index < events.length; index++) {
  7598. var event = events[index];
  7599. window.removeEventListener(event.name, event.handler);
  7600. try {
  7601. if (window.parent) {
  7602. window.parent.removeEventListener(event.name, event.handler);
  7603. }
  7604. }
  7605. catch (e) {
  7606. // Silently fails...
  7607. }
  7608. }
  7609. };
  7610. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7611. if (mimeType === void 0) { mimeType = "image/png"; }
  7612. // Read the contents of the framebuffer
  7613. var numberOfChannelsByLine = width * 4;
  7614. var halfHeight = height / 2;
  7615. //Reading datas from WebGL
  7616. var data = engine.readPixels(0, 0, width, height);
  7617. //To flip image on Y axis.
  7618. for (var i = 0; i < halfHeight; i++) {
  7619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7620. var currentCell = j + i * numberOfChannelsByLine;
  7621. var targetLine = height - i - 1;
  7622. var targetCell = j + targetLine * numberOfChannelsByLine;
  7623. var temp = data[currentCell];
  7624. data[currentCell] = data[targetCell];
  7625. data[targetCell] = temp;
  7626. }
  7627. }
  7628. // Create a 2D canvas to store the result
  7629. if (!screenshotCanvas) {
  7630. screenshotCanvas = document.createElement('canvas');
  7631. }
  7632. screenshotCanvas.width = width;
  7633. screenshotCanvas.height = height;
  7634. var context = screenshotCanvas.getContext('2d');
  7635. if (context) {
  7636. // Copy the pixels to a 2D canvas
  7637. var imageData = context.createImageData(width, height);
  7638. var castData = (imageData.data);
  7639. castData.set(data);
  7640. context.putImageData(imageData, 0, 0);
  7641. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7642. }
  7643. };
  7644. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7645. if (mimeType === void 0) { mimeType = "image/png"; }
  7646. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7647. if (successCallback) {
  7648. successCallback(base64Image);
  7649. }
  7650. else {
  7651. // We need HTMLCanvasElement.toBlob for HD screenshots
  7652. if (!screenshotCanvas.toBlob) {
  7653. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7654. screenshotCanvas.toBlob = function (callback, type, quality) {
  7655. var _this = this;
  7656. setTimeout(function () {
  7657. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7658. for (var i = 0; i < len; i++) {
  7659. arr[i] = binStr.charCodeAt(i);
  7660. }
  7661. callback(new Blob([arr], { type: type || 'image/png' }));
  7662. });
  7663. };
  7664. }
  7665. screenshotCanvas.toBlob(function (blob) {
  7666. var url = URL.createObjectURL(blob);
  7667. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7668. if (("download" in document.createElement("a"))) {
  7669. var a = window.document.createElement("a");
  7670. a.href = url;
  7671. if (fileName) {
  7672. a.setAttribute("download", fileName);
  7673. }
  7674. else {
  7675. var date = new Date();
  7676. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7677. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7678. }
  7679. window.document.body.appendChild(a);
  7680. a.addEventListener("click", function () {
  7681. if (a.parentElement) {
  7682. a.parentElement.removeChild(a);
  7683. }
  7684. });
  7685. a.click();
  7686. }
  7687. else {
  7688. var newWindow = window.open("");
  7689. if (!newWindow)
  7690. return;
  7691. var img = newWindow.document.createElement("img");
  7692. img.onload = function () {
  7693. // no longer need to read the blob so it's revoked
  7694. URL.revokeObjectURL(url);
  7695. };
  7696. img.src = url;
  7697. newWindow.document.body.appendChild(img);
  7698. }
  7699. });
  7700. }
  7701. };
  7702. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7703. if (mimeType === void 0) { mimeType = "image/png"; }
  7704. var width;
  7705. var height;
  7706. // If a precision value is specified
  7707. if (size.precision) {
  7708. width = Math.round(engine.getRenderWidth() * size.precision);
  7709. height = Math.round(width / engine.getAspectRatio(camera));
  7710. }
  7711. else if (size.width && size.height) {
  7712. width = size.width;
  7713. height = size.height;
  7714. }
  7715. else if (size.width && !size.height) {
  7716. width = size.width;
  7717. height = Math.round(width / engine.getAspectRatio(camera));
  7718. }
  7719. else if (size.height && !size.width) {
  7720. height = size.height;
  7721. width = Math.round(height * engine.getAspectRatio(camera));
  7722. }
  7723. else if (!isNaN(size)) {
  7724. height = size;
  7725. width = size;
  7726. }
  7727. else {
  7728. Tools.Error("Invalid 'size' parameter !");
  7729. return;
  7730. }
  7731. if (!screenshotCanvas) {
  7732. screenshotCanvas = document.createElement('canvas');
  7733. }
  7734. screenshotCanvas.width = width;
  7735. screenshotCanvas.height = height;
  7736. var renderContext = screenshotCanvas.getContext("2d");
  7737. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7738. var newWidth = width;
  7739. var newHeight = newWidth / ratio;
  7740. if (newHeight > height) {
  7741. newHeight = height;
  7742. newWidth = newHeight * ratio;
  7743. }
  7744. var offsetX = Math.max(0, width - newWidth) / 2;
  7745. var offsetY = Math.max(0, height - newHeight) / 2;
  7746. var renderingCanvas = engine.getRenderingCanvas();
  7747. if (renderContext && renderingCanvas) {
  7748. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7749. }
  7750. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7751. };
  7752. /**
  7753. * Generates an image screenshot from the specified camera.
  7754. *
  7755. * @param engine The engine to use for rendering
  7756. * @param camera The camera to use for rendering
  7757. * @param size This parameter can be set to a single number or to an object with the
  7758. * following (optional) properties: precision, width, height. If a single number is passed,
  7759. * it will be used for both width and height. If an object is passed, the screenshot size
  7760. * will be derived from the parameters. The precision property is a multiplier allowing
  7761. * rendering at a higher or lower resolution.
  7762. * @param successCallback The callback receives a single parameter which contains the
  7763. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7764. * src parameter of an <img> to display it.
  7765. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7766. * Check your browser for supported MIME types.
  7767. * @param samples Texture samples (default: 1)
  7768. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7769. * @param fileName A name for for the downloaded file.
  7770. * @constructor
  7771. */
  7772. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7773. if (mimeType === void 0) { mimeType = "image/png"; }
  7774. if (samples === void 0) { samples = 1; }
  7775. if (antialiasing === void 0) { antialiasing = false; }
  7776. var width;
  7777. var height;
  7778. //If a precision value is specified
  7779. if (size.precision) {
  7780. width = Math.round(engine.getRenderWidth() * size.precision);
  7781. height = Math.round(width / engine.getAspectRatio(camera));
  7782. size = { width: width, height: height };
  7783. }
  7784. else if (size.width && size.height) {
  7785. width = size.width;
  7786. height = size.height;
  7787. }
  7788. else if (size.width && !size.height) {
  7789. width = size.width;
  7790. height = Math.round(width / engine.getAspectRatio(camera));
  7791. size = { width: width, height: height };
  7792. }
  7793. else if (size.height && !size.width) {
  7794. height = size.height;
  7795. width = Math.round(height * engine.getAspectRatio(camera));
  7796. size = { width: width, height: height };
  7797. }
  7798. else if (!isNaN(size)) {
  7799. height = size;
  7800. width = size;
  7801. }
  7802. else {
  7803. Tools.Error("Invalid 'size' parameter !");
  7804. return;
  7805. }
  7806. var scene = camera.getScene();
  7807. var previousCamera = null;
  7808. if (scene.activeCamera !== camera) {
  7809. previousCamera = scene.activeCamera;
  7810. scene.activeCamera = camera;
  7811. }
  7812. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7813. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7814. texture.renderList = null;
  7815. texture.samples = samples;
  7816. if (antialiasing) {
  7817. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7818. }
  7819. texture.onAfterRenderObservable.add(function () {
  7820. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7821. });
  7822. scene.incrementRenderId();
  7823. scene.resetCachedMaterial();
  7824. texture.render(true);
  7825. texture.dispose();
  7826. if (previousCamera) {
  7827. scene.activeCamera = previousCamera;
  7828. }
  7829. camera.getProjectionMatrix(true); // Force cache refresh;
  7830. };
  7831. // XHR response validator for local file scenario
  7832. Tools.ValidateXHRData = function (xhr, dataType) {
  7833. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7834. if (dataType === void 0) { dataType = 7; }
  7835. try {
  7836. if (dataType & 1) {
  7837. if (xhr.responseText && xhr.responseText.length > 0) {
  7838. return true;
  7839. }
  7840. else if (dataType === 1) {
  7841. return false;
  7842. }
  7843. }
  7844. if (dataType & 2) {
  7845. // Check header width and height since there is no "TGA" magic number
  7846. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7847. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7848. return true;
  7849. }
  7850. else if (dataType === 2) {
  7851. return false;
  7852. }
  7853. }
  7854. if (dataType & 4) {
  7855. // Check for the "DDS" magic number
  7856. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7857. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7858. return true;
  7859. }
  7860. else {
  7861. return false;
  7862. }
  7863. }
  7864. }
  7865. catch (e) {
  7866. // Global protection
  7867. }
  7868. return false;
  7869. };
  7870. /**
  7871. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7872. * Be aware Math.random() could cause collisions, but:
  7873. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  7874. */
  7875. Tools.RandomId = function () {
  7876. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7877. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7878. return v.toString(16);
  7879. });
  7880. };
  7881. /**
  7882. * Test if the given uri is a base64 string.
  7883. * @param uri The uri to test
  7884. * @return True if the uri is a base64 string or false otherwise.
  7885. */
  7886. Tools.IsBase64 = function (uri) {
  7887. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  7888. };
  7889. /**
  7890. * Decode the given base64 uri.
  7891. * @param uri The uri to decode
  7892. * @return The decoded base64 data.
  7893. */
  7894. Tools.DecodeBase64 = function (uri) {
  7895. var decodedString = atob(uri.split(",")[1]);
  7896. var bufferLength = decodedString.length;
  7897. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  7898. for (var i = 0; i < bufferLength; i++) {
  7899. bufferView[i] = decodedString.charCodeAt(i);
  7900. }
  7901. return bufferView.buffer;
  7902. };
  7903. Object.defineProperty(Tools, "NoneLogLevel", {
  7904. get: function () {
  7905. return Tools._NoneLogLevel;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(Tools, "MessageLogLevel", {
  7911. get: function () {
  7912. return Tools._MessageLogLevel;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Tools, "WarningLogLevel", {
  7918. get: function () {
  7919. return Tools._WarningLogLevel;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Tools, "ErrorLogLevel", {
  7925. get: function () {
  7926. return Tools._ErrorLogLevel;
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(Tools, "AllLogLevel", {
  7932. get: function () {
  7933. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Tools._AddLogEntry = function (entry) {
  7939. Tools._LogCache = entry + Tools._LogCache;
  7940. if (Tools.OnNewCacheEntry) {
  7941. Tools.OnNewCacheEntry(entry);
  7942. }
  7943. };
  7944. Tools._FormatMessage = function (message) {
  7945. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7946. var date = new Date();
  7947. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7948. };
  7949. Tools._LogDisabled = function (message) {
  7950. // nothing to do
  7951. };
  7952. Tools._LogEnabled = function (message) {
  7953. var formattedMessage = Tools._FormatMessage(message);
  7954. console.log("BJS - " + formattedMessage);
  7955. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7956. Tools._AddLogEntry(entry);
  7957. };
  7958. Tools._WarnDisabled = function (message) {
  7959. // nothing to do
  7960. };
  7961. Tools._WarnEnabled = function (message) {
  7962. var formattedMessage = Tools._FormatMessage(message);
  7963. console.warn("BJS - " + formattedMessage);
  7964. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7965. Tools._AddLogEntry(entry);
  7966. };
  7967. Tools._ErrorDisabled = function (message) {
  7968. // nothing to do
  7969. };
  7970. Tools._ErrorEnabled = function (message) {
  7971. Tools.errorsCount++;
  7972. var formattedMessage = Tools._FormatMessage(message);
  7973. console.error("BJS - " + formattedMessage);
  7974. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7975. Tools._AddLogEntry(entry);
  7976. };
  7977. Object.defineProperty(Tools, "LogCache", {
  7978. get: function () {
  7979. return Tools._LogCache;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Tools.ClearLogCache = function () {
  7985. Tools._LogCache = "";
  7986. Tools.errorsCount = 0;
  7987. };
  7988. Object.defineProperty(Tools, "LogLevels", {
  7989. set: function (level) {
  7990. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7991. Tools.Log = Tools._LogEnabled;
  7992. }
  7993. else {
  7994. Tools.Log = Tools._LogDisabled;
  7995. }
  7996. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7997. Tools.Warn = Tools._WarnEnabled;
  7998. }
  7999. else {
  8000. Tools.Warn = Tools._WarnDisabled;
  8001. }
  8002. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8003. Tools.Error = Tools._ErrorEnabled;
  8004. }
  8005. else {
  8006. Tools.Error = Tools._ErrorDisabled;
  8007. }
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Tools.IsWindowObjectExist = function () {
  8013. return (typeof window) !== "undefined";
  8014. };
  8015. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8016. get: function () {
  8017. return Tools._PerformanceNoneLogLevel;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8023. get: function () {
  8024. return Tools._PerformanceUserMarkLogLevel;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8030. get: function () {
  8031. return Tools._PerformanceConsoleLogLevel;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8037. set: function (level) {
  8038. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8039. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8040. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8041. return;
  8042. }
  8043. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8044. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8045. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8046. return;
  8047. }
  8048. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8049. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8055. };
  8056. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8057. };
  8058. Tools._StartUserMark = function (counterName, condition) {
  8059. if (condition === void 0) { condition = true; }
  8060. if (!Tools._performance) {
  8061. if (!Tools.IsWindowObjectExist()) {
  8062. return;
  8063. }
  8064. Tools._performance = window.performance;
  8065. }
  8066. if (!condition || !Tools._performance.mark) {
  8067. return;
  8068. }
  8069. Tools._performance.mark(counterName + "-Begin");
  8070. };
  8071. Tools._EndUserMark = function (counterName, condition) {
  8072. if (condition === void 0) { condition = true; }
  8073. if (!condition || !Tools._performance.mark) {
  8074. return;
  8075. }
  8076. Tools._performance.mark(counterName + "-End");
  8077. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8078. };
  8079. Tools._StartPerformanceConsole = function (counterName, condition) {
  8080. if (condition === void 0) { condition = true; }
  8081. if (!condition) {
  8082. return;
  8083. }
  8084. Tools._StartUserMark(counterName, condition);
  8085. if (console.time) {
  8086. console.time(counterName);
  8087. }
  8088. };
  8089. Tools._EndPerformanceConsole = function (counterName, condition) {
  8090. if (condition === void 0) { condition = true; }
  8091. if (!condition) {
  8092. return;
  8093. }
  8094. Tools._EndUserMark(counterName, condition);
  8095. if (console.time) {
  8096. console.timeEnd(counterName);
  8097. }
  8098. };
  8099. Object.defineProperty(Tools, "Now", {
  8100. get: function () {
  8101. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8102. return window.performance.now();
  8103. }
  8104. return new Date().getTime();
  8105. },
  8106. enumerable: true,
  8107. configurable: true
  8108. });
  8109. /**
  8110. * This method will return the name of the class used to create the instance of the given object.
  8111. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8112. * @param object the object to get the class name from
  8113. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8114. */
  8115. Tools.GetClassName = function (object, isType) {
  8116. if (isType === void 0) { isType = false; }
  8117. var name = null;
  8118. if (!isType && object.getClassName) {
  8119. name = object.getClassName();
  8120. }
  8121. else {
  8122. if (object instanceof Object) {
  8123. var classObj = isType ? object : Object.getPrototypeOf(object);
  8124. name = classObj.constructor["__bjsclassName__"];
  8125. }
  8126. if (!name) {
  8127. name = typeof object;
  8128. }
  8129. }
  8130. return name;
  8131. };
  8132. Tools.First = function (array, predicate) {
  8133. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8134. var el = array_1[_i];
  8135. if (predicate(el)) {
  8136. return el;
  8137. }
  8138. }
  8139. return null;
  8140. };
  8141. /**
  8142. * This method will return the name of the full name of the class, including its owning module (if any).
  8143. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  8144. * @param object the object to get the class name from
  8145. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  8146. */
  8147. Tools.getFullClassName = function (object, isType) {
  8148. if (isType === void 0) { isType = false; }
  8149. var className = null;
  8150. var moduleName = null;
  8151. if (!isType && object.getClassName) {
  8152. className = object.getClassName();
  8153. }
  8154. else {
  8155. if (object instanceof Object) {
  8156. var classObj = isType ? object : Object.getPrototypeOf(object);
  8157. className = classObj.constructor["__bjsclassName__"];
  8158. moduleName = classObj.constructor["__bjsmoduleName__"];
  8159. }
  8160. if (!className) {
  8161. className = typeof object;
  8162. }
  8163. }
  8164. if (!className) {
  8165. return null;
  8166. }
  8167. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8168. };
  8169. /**
  8170. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  8171. * @param array
  8172. */
  8173. Tools.arrayOrStringFeeder = function (array) {
  8174. return function (index) {
  8175. if (index >= array.length) {
  8176. return null;
  8177. }
  8178. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8179. if (val && val.getHashCode) {
  8180. val = val.getHashCode();
  8181. }
  8182. if (typeof val === "string") {
  8183. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8184. }
  8185. return val;
  8186. };
  8187. };
  8188. /**
  8189. * Compute the hashCode of a stream of number
  8190. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8191. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8192. * @return the hash code computed
  8193. */
  8194. Tools.hashCodeFromStream = function (feeder) {
  8195. // Based from here: http://stackoverflow.com/a/7616484/802124
  8196. var hash = 0;
  8197. var index = 0;
  8198. var chr = feeder(index++);
  8199. while (chr != null) {
  8200. hash = ((hash << 5) - hash) + chr;
  8201. hash |= 0; // Convert to 32bit integer
  8202. chr = feeder(index++);
  8203. }
  8204. return hash;
  8205. };
  8206. Tools.BaseUrl = "";
  8207. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8208. /**
  8209. * Default behaviour for cors in the application.
  8210. * It can be a string if the expected behavior is identical in the entire app.
  8211. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8212. */
  8213. Tools.CorsBehavior = "anonymous";
  8214. Tools.UseFallbackTexture = true;
  8215. /**
  8216. * Use this object to register external classes like custom textures or material
  8217. * to allow the laoders to instantiate them
  8218. */
  8219. Tools.RegisteredExternalClasses = {};
  8220. // Used in case of a texture loading problem
  8221. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  8222. Tools.PreprocessUrl = function (url) {
  8223. return url;
  8224. };
  8225. // Logs
  8226. Tools._NoneLogLevel = 0;
  8227. Tools._MessageLogLevel = 1;
  8228. Tools._WarningLogLevel = 2;
  8229. Tools._ErrorLogLevel = 4;
  8230. Tools._LogCache = "";
  8231. Tools.errorsCount = 0;
  8232. Tools.Log = Tools._LogEnabled;
  8233. Tools.Warn = Tools._WarnEnabled;
  8234. Tools.Error = Tools._ErrorEnabled;
  8235. // Performances
  8236. Tools._PerformanceNoneLogLevel = 0;
  8237. Tools._PerformanceUserMarkLogLevel = 1;
  8238. Tools._PerformanceConsoleLogLevel = 2;
  8239. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8240. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8241. return Tools;
  8242. }());
  8243. BABYLON.Tools = Tools;
  8244. /**
  8245. * This class is used to track a performance counter which is number based.
  8246. * The user has access to many properties which give statistics of different nature
  8247. *
  8248. * The implementer can track two kinds of Performance Counter: time and count
  8249. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  8250. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  8251. */
  8252. var PerfCounter = /** @class */ (function () {
  8253. function PerfCounter() {
  8254. this._startMonitoringTime = 0;
  8255. this._min = 0;
  8256. this._max = 0;
  8257. this._average = 0;
  8258. this._lastSecAverage = 0;
  8259. this._current = 0;
  8260. this._totalValueCount = 0;
  8261. this._totalAccumulated = 0;
  8262. this._lastSecAccumulated = 0;
  8263. this._lastSecTime = 0;
  8264. this._lastSecValueCount = 0;
  8265. }
  8266. Object.defineProperty(PerfCounter.prototype, "min", {
  8267. /**
  8268. * Returns the smallest value ever
  8269. */
  8270. get: function () {
  8271. return this._min;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(PerfCounter.prototype, "max", {
  8277. /**
  8278. * Returns the biggest value ever
  8279. */
  8280. get: function () {
  8281. return this._max;
  8282. },
  8283. enumerable: true,
  8284. configurable: true
  8285. });
  8286. Object.defineProperty(PerfCounter.prototype, "average", {
  8287. /**
  8288. * Returns the average value since the performance counter is running
  8289. */
  8290. get: function () {
  8291. return this._average;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8297. /**
  8298. * Returns the average value of the last second the counter was monitored
  8299. */
  8300. get: function () {
  8301. return this._lastSecAverage;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(PerfCounter.prototype, "current", {
  8307. /**
  8308. * Returns the current value
  8309. */
  8310. get: function () {
  8311. return this._current;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(PerfCounter.prototype, "total", {
  8317. get: function () {
  8318. return this._totalAccumulated;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(PerfCounter.prototype, "count", {
  8324. get: function () {
  8325. return this._totalValueCount;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. /**
  8331. * Call this method to start monitoring a new frame.
  8332. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  8333. */
  8334. PerfCounter.prototype.fetchNewFrame = function () {
  8335. this._totalValueCount++;
  8336. this._current = 0;
  8337. this._lastSecValueCount++;
  8338. };
  8339. /**
  8340. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8341. * @param newCount the count value to add to the monitored count
  8342. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  8343. */
  8344. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8345. if (!PerfCounter.Enabled) {
  8346. return;
  8347. }
  8348. this._current += newCount;
  8349. if (fetchResult) {
  8350. this._fetchResult();
  8351. }
  8352. };
  8353. /**
  8354. * Start monitoring this performance counter
  8355. */
  8356. PerfCounter.prototype.beginMonitoring = function () {
  8357. if (!PerfCounter.Enabled) {
  8358. return;
  8359. }
  8360. this._startMonitoringTime = Tools.Now;
  8361. };
  8362. /**
  8363. * Compute the time lapsed since the previous beginMonitoring() call.
  8364. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  8365. */
  8366. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8367. if (newFrame === void 0) { newFrame = true; }
  8368. if (!PerfCounter.Enabled) {
  8369. return;
  8370. }
  8371. if (newFrame) {
  8372. this.fetchNewFrame();
  8373. }
  8374. var currentTime = Tools.Now;
  8375. this._current = currentTime - this._startMonitoringTime;
  8376. if (newFrame) {
  8377. this._fetchResult();
  8378. }
  8379. };
  8380. PerfCounter.prototype._fetchResult = function () {
  8381. this._totalAccumulated += this._current;
  8382. this._lastSecAccumulated += this._current;
  8383. // Min/Max update
  8384. this._min = Math.min(this._min, this._current);
  8385. this._max = Math.max(this._max, this._current);
  8386. this._average = this._totalAccumulated / this._totalValueCount;
  8387. // Reset last sec?
  8388. var now = Tools.Now;
  8389. if ((now - this._lastSecTime) > 1000) {
  8390. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8391. this._lastSecTime = now;
  8392. this._lastSecAccumulated = 0;
  8393. this._lastSecValueCount = 0;
  8394. }
  8395. };
  8396. PerfCounter.Enabled = true;
  8397. return PerfCounter;
  8398. }());
  8399. BABYLON.PerfCounter = PerfCounter;
  8400. /**
  8401. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8402. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8403. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8404. * @param name The name of the class, case should be preserved
  8405. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8406. */
  8407. function className(name, module) {
  8408. return function (target) {
  8409. target["__bjsclassName__"] = name;
  8410. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8411. };
  8412. }
  8413. BABYLON.className = className;
  8414. /**
  8415. * An implementation of a loop for asynchronous functions.
  8416. */
  8417. var AsyncLoop = /** @class */ (function () {
  8418. /**
  8419. * Constroctor.
  8420. * @param iterations the number of iterations.
  8421. * @param _fn the function to run each iteration
  8422. * @param _successCallback the callback that will be called upon succesful execution
  8423. * @param offset starting offset.
  8424. */
  8425. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8426. if (offset === void 0) { offset = 0; }
  8427. this.iterations = iterations;
  8428. this._fn = _fn;
  8429. this._successCallback = _successCallback;
  8430. this.index = offset - 1;
  8431. this._done = false;
  8432. }
  8433. /**
  8434. * Execute the next iteration. Must be called after the last iteration was finished.
  8435. */
  8436. AsyncLoop.prototype.executeNext = function () {
  8437. if (!this._done) {
  8438. if (this.index + 1 < this.iterations) {
  8439. ++this.index;
  8440. this._fn(this);
  8441. }
  8442. else {
  8443. this.breakLoop();
  8444. }
  8445. }
  8446. };
  8447. /**
  8448. * Break the loop and run the success callback.
  8449. */
  8450. AsyncLoop.prototype.breakLoop = function () {
  8451. this._done = true;
  8452. this._successCallback();
  8453. };
  8454. /**
  8455. * Helper function
  8456. */
  8457. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8458. if (offset === void 0) { offset = 0; }
  8459. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8460. loop.executeNext();
  8461. return loop;
  8462. };
  8463. /**
  8464. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8465. * @param iterations total number of iterations
  8466. * @param syncedIterations number of synchronous iterations in each async iteration.
  8467. * @param fn the function to call each iteration.
  8468. * @param callback a success call back that will be called when iterating stops.
  8469. * @param breakFunction a break condition (optional)
  8470. * @param timeout timeout settings for the setTimeout function. default - 0.
  8471. * @constructor
  8472. */
  8473. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8474. if (timeout === void 0) { timeout = 0; }
  8475. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8476. if (breakFunction && breakFunction())
  8477. loop.breakLoop();
  8478. else {
  8479. setTimeout(function () {
  8480. for (var i = 0; i < syncedIterations; ++i) {
  8481. var iteration = (loop.index * syncedIterations) + i;
  8482. if (iteration >= iterations)
  8483. break;
  8484. fn(iteration);
  8485. if (breakFunction && breakFunction()) {
  8486. loop.breakLoop();
  8487. break;
  8488. }
  8489. }
  8490. loop.executeNext();
  8491. }, timeout);
  8492. }
  8493. }, callback);
  8494. };
  8495. return AsyncLoop;
  8496. }());
  8497. BABYLON.AsyncLoop = AsyncLoop;
  8498. })(BABYLON || (BABYLON = {}));
  8499. //# sourceMappingURL=babylon.tools.js.map
  8500. var BABYLON;
  8501. (function (BABYLON) {
  8502. var PromiseStates;
  8503. (function (PromiseStates) {
  8504. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8505. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8506. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8507. })(PromiseStates || (PromiseStates = {}));
  8508. var FulFillmentAgregator = /** @class */ (function () {
  8509. function FulFillmentAgregator() {
  8510. this.count = 0;
  8511. this.target = 0;
  8512. this.results = [];
  8513. }
  8514. return FulFillmentAgregator;
  8515. }());
  8516. var InternalPromise = /** @class */ (function () {
  8517. function InternalPromise(resolver) {
  8518. var _this = this;
  8519. this._state = PromiseStates.Pending;
  8520. this._children = new Array();
  8521. this._rejectWasConsumed = false;
  8522. if (!resolver) {
  8523. return;
  8524. }
  8525. try {
  8526. resolver(function (value) {
  8527. _this._resolve(value);
  8528. }, function (reason) {
  8529. _this._reject(reason);
  8530. });
  8531. }
  8532. catch (e) {
  8533. this._reject(e.message);
  8534. }
  8535. }
  8536. Object.defineProperty(InternalPromise.prototype, "state", {
  8537. get: function () {
  8538. return this._state;
  8539. },
  8540. enumerable: true,
  8541. configurable: true
  8542. });
  8543. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8544. get: function () {
  8545. return this._state === PromiseStates.Fulfilled;
  8546. },
  8547. enumerable: true,
  8548. configurable: true
  8549. });
  8550. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8551. get: function () {
  8552. return this._state === PromiseStates.Rejected;
  8553. },
  8554. enumerable: true,
  8555. configurable: true
  8556. });
  8557. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8558. get: function () {
  8559. return this._state === PromiseStates.Pending;
  8560. },
  8561. enumerable: true,
  8562. configurable: true
  8563. });
  8564. InternalPromise.prototype.value = function () {
  8565. if (!this.isFulfilled) {
  8566. throw new Error("Promise is not fulfilled");
  8567. }
  8568. return this._result;
  8569. };
  8570. InternalPromise.prototype.reason = function () {
  8571. if (!this.isRejected) {
  8572. throw new Error("Promise is not rejected");
  8573. }
  8574. return this._reason;
  8575. };
  8576. InternalPromise.prototype.catch = function (onRejected) {
  8577. return this.then(undefined, onRejected);
  8578. };
  8579. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8580. var newPromise = new InternalPromise();
  8581. newPromise._onFulfilled = onFulfilled;
  8582. newPromise._onRejected = onRejected;
  8583. // Composition
  8584. this._children.push(newPromise);
  8585. if (this._state !== PromiseStates.Pending) {
  8586. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8587. var returnedValue = newPromise._resolve(this._result);
  8588. if (returnedValue !== undefined && returnedValue !== null) {
  8589. if (returnedValue._state !== undefined) {
  8590. var returnedPromise = returnedValue;
  8591. newPromise._children.push(returnedPromise);
  8592. newPromise = returnedPromise;
  8593. }
  8594. else {
  8595. newPromise._result = returnedValue;
  8596. }
  8597. }
  8598. }
  8599. else {
  8600. newPromise._reject(this._reason);
  8601. }
  8602. }
  8603. return newPromise;
  8604. };
  8605. InternalPromise.prototype._moveChildren = function (children) {
  8606. this._children = children.splice(0, children.length);
  8607. if (this.isFulfilled) {
  8608. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8609. var child = _a[_i];
  8610. child._resolve(this._result);
  8611. }
  8612. }
  8613. else if (this.isRejected) {
  8614. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8615. var child = _c[_b];
  8616. child._reject(this._reason);
  8617. }
  8618. }
  8619. };
  8620. InternalPromise.prototype._resolve = function (value) {
  8621. try {
  8622. this._state = PromiseStates.Fulfilled;
  8623. this._result = value;
  8624. var returnedValue = null;
  8625. if (this._onFulfilled) {
  8626. returnedValue = this._onFulfilled(value);
  8627. }
  8628. if (returnedValue !== undefined && returnedValue !== null) {
  8629. if (returnedValue._state !== undefined) {
  8630. // Transmit children
  8631. var returnedPromise = returnedValue;
  8632. returnedPromise._moveChildren(this._children);
  8633. }
  8634. }
  8635. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8636. var child = _a[_i];
  8637. child._resolve(value);
  8638. }
  8639. return returnedValue;
  8640. }
  8641. catch (e) {
  8642. this._reject(e.message);
  8643. }
  8644. return null;
  8645. };
  8646. InternalPromise.prototype._reject = function (reason) {
  8647. this._state = PromiseStates.Rejected;
  8648. this._reason = reason;
  8649. if (this._onRejected) {
  8650. this._onRejected(reason);
  8651. this._rejectWasConsumed = true;
  8652. }
  8653. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8654. var child = _a[_i];
  8655. if (this._rejectWasConsumed) {
  8656. child._resolve(null);
  8657. }
  8658. else {
  8659. child._reject(reason);
  8660. }
  8661. }
  8662. };
  8663. InternalPromise.resolve = function (value) {
  8664. var newPromise = new InternalPromise();
  8665. newPromise._resolve(value);
  8666. return newPromise;
  8667. };
  8668. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8669. promise.then(function (value) {
  8670. agregator.results[index] = value;
  8671. agregator.count++;
  8672. if (agregator.count === agregator.target) {
  8673. agregator.rootPromise._resolve(agregator.results);
  8674. }
  8675. return null;
  8676. }, function (reason) {
  8677. if (!agregator.rootPromise.isRejected) {
  8678. agregator.rootPromise._reject(reason);
  8679. }
  8680. });
  8681. };
  8682. InternalPromise.all = function (promises) {
  8683. var newPromise = new InternalPromise();
  8684. var agregator = new FulFillmentAgregator();
  8685. agregator.target = promises.length;
  8686. agregator.rootPromise = newPromise;
  8687. for (var index = 0; index < promises.length; index++) {
  8688. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8689. }
  8690. return newPromise;
  8691. };
  8692. return InternalPromise;
  8693. }());
  8694. /**
  8695. * Helper class that provides a small promise polyfill
  8696. */
  8697. var PromisePolyfill = /** @class */ (function () {
  8698. function PromisePolyfill() {
  8699. }
  8700. /**
  8701. * Static function used to check if the polyfill is required
  8702. * If this is the case then the function will inject the polyfill to window.Promise
  8703. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8704. */
  8705. PromisePolyfill.Apply = function (force) {
  8706. if (force === void 0) { force = false; }
  8707. if (force || typeof Promise === 'undefined') {
  8708. var root = window;
  8709. root.Promise = InternalPromise;
  8710. }
  8711. };
  8712. return PromisePolyfill;
  8713. }());
  8714. BABYLON.PromisePolyfill = PromisePolyfill;
  8715. })(BABYLON || (BABYLON = {}));
  8716. //# sourceMappingURL=babylon.promise.js.map
  8717. var BABYLON;
  8718. (function (BABYLON) {
  8719. var _AlphaState = /** @class */ (function () {
  8720. /**
  8721. * Initializes the state.
  8722. */
  8723. function _AlphaState() {
  8724. this._isAlphaBlendDirty = false;
  8725. this._isBlendFunctionParametersDirty = false;
  8726. this._isBlendEquationParametersDirty = false;
  8727. this._isBlendConstantsDirty = false;
  8728. this._alphaBlend = false;
  8729. this._blendFunctionParameters = new Array(4);
  8730. this._blendEquationParameters = new Array(2);
  8731. this._blendConstants = new Array(4);
  8732. this.reset();
  8733. }
  8734. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8735. get: function () {
  8736. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8742. get: function () {
  8743. return this._alphaBlend;
  8744. },
  8745. set: function (value) {
  8746. if (this._alphaBlend === value) {
  8747. return;
  8748. }
  8749. this._alphaBlend = value;
  8750. this._isAlphaBlendDirty = true;
  8751. },
  8752. enumerable: true,
  8753. configurable: true
  8754. });
  8755. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8756. if (this._blendConstants[0] === r &&
  8757. this._blendConstants[1] === g &&
  8758. this._blendConstants[2] === b &&
  8759. this._blendConstants[3] === a) {
  8760. return;
  8761. }
  8762. this._blendConstants[0] = r;
  8763. this._blendConstants[1] = g;
  8764. this._blendConstants[2] = b;
  8765. this._blendConstants[3] = a;
  8766. this._isBlendConstantsDirty = true;
  8767. };
  8768. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8769. if (this._blendFunctionParameters[0] === value0 &&
  8770. this._blendFunctionParameters[1] === value1 &&
  8771. this._blendFunctionParameters[2] === value2 &&
  8772. this._blendFunctionParameters[3] === value3) {
  8773. return;
  8774. }
  8775. this._blendFunctionParameters[0] = value0;
  8776. this._blendFunctionParameters[1] = value1;
  8777. this._blendFunctionParameters[2] = value2;
  8778. this._blendFunctionParameters[3] = value3;
  8779. this._isBlendFunctionParametersDirty = true;
  8780. };
  8781. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8782. if (this._blendEquationParameters[0] === rgb &&
  8783. this._blendEquationParameters[1] === alpha) {
  8784. return;
  8785. }
  8786. this._blendEquationParameters[0] = rgb;
  8787. this._blendEquationParameters[1] = alpha;
  8788. this._isBlendEquationParametersDirty = true;
  8789. };
  8790. _AlphaState.prototype.reset = function () {
  8791. this._alphaBlend = false;
  8792. this._blendFunctionParameters[0] = null;
  8793. this._blendFunctionParameters[1] = null;
  8794. this._blendFunctionParameters[2] = null;
  8795. this._blendFunctionParameters[3] = null;
  8796. this._blendEquationParameters[0] = null;
  8797. this._blendEquationParameters[1] = null;
  8798. this._blendConstants[0] = null;
  8799. this._blendConstants[1] = null;
  8800. this._blendConstants[2] = null;
  8801. this._blendConstants[3] = null;
  8802. this._isAlphaBlendDirty = true;
  8803. this._isBlendFunctionParametersDirty = false;
  8804. this._isBlendEquationParametersDirty = false;
  8805. this._isBlendConstantsDirty = false;
  8806. };
  8807. _AlphaState.prototype.apply = function (gl) {
  8808. if (!this.isDirty) {
  8809. return;
  8810. }
  8811. // Alpha blend
  8812. if (this._isAlphaBlendDirty) {
  8813. if (this._alphaBlend) {
  8814. gl.enable(gl.BLEND);
  8815. }
  8816. else {
  8817. gl.disable(gl.BLEND);
  8818. }
  8819. this._isAlphaBlendDirty = false;
  8820. }
  8821. // Alpha function
  8822. if (this._isBlendFunctionParametersDirty) {
  8823. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8824. this._isBlendFunctionParametersDirty = false;
  8825. }
  8826. // Alpha equation
  8827. if (this._isBlendEquationParametersDirty) {
  8828. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8829. this._isBlendEquationParametersDirty = false;
  8830. }
  8831. // Constants
  8832. if (this._isBlendConstantsDirty) {
  8833. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8834. this._isBlendConstantsDirty = false;
  8835. }
  8836. };
  8837. return _AlphaState;
  8838. }());
  8839. BABYLON._AlphaState = _AlphaState;
  8840. })(BABYLON || (BABYLON = {}));
  8841. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8842. var BABYLON;
  8843. (function (BABYLON) {
  8844. var _DepthCullingState = /** @class */ (function () {
  8845. /**
  8846. * Initializes the state.
  8847. */
  8848. function _DepthCullingState() {
  8849. this._isDepthTestDirty = false;
  8850. this._isDepthMaskDirty = false;
  8851. this._isDepthFuncDirty = false;
  8852. this._isCullFaceDirty = false;
  8853. this._isCullDirty = false;
  8854. this._isZOffsetDirty = false;
  8855. this._isFrontFaceDirty = false;
  8856. this.reset();
  8857. }
  8858. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8859. get: function () {
  8860. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8861. },
  8862. enumerable: true,
  8863. configurable: true
  8864. });
  8865. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8866. get: function () {
  8867. return this._zOffset;
  8868. },
  8869. set: function (value) {
  8870. if (this._zOffset === value) {
  8871. return;
  8872. }
  8873. this._zOffset = value;
  8874. this._isZOffsetDirty = true;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8880. get: function () {
  8881. return this._cullFace;
  8882. },
  8883. set: function (value) {
  8884. if (this._cullFace === value) {
  8885. return;
  8886. }
  8887. this._cullFace = value;
  8888. this._isCullFaceDirty = true;
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8894. get: function () {
  8895. return this._cull;
  8896. },
  8897. set: function (value) {
  8898. if (this._cull === value) {
  8899. return;
  8900. }
  8901. this._cull = value;
  8902. this._isCullDirty = true;
  8903. },
  8904. enumerable: true,
  8905. configurable: true
  8906. });
  8907. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8908. get: function () {
  8909. return this._depthFunc;
  8910. },
  8911. set: function (value) {
  8912. if (this._depthFunc === value) {
  8913. return;
  8914. }
  8915. this._depthFunc = value;
  8916. this._isDepthFuncDirty = true;
  8917. },
  8918. enumerable: true,
  8919. configurable: true
  8920. });
  8921. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8922. get: function () {
  8923. return this._depthMask;
  8924. },
  8925. set: function (value) {
  8926. if (this._depthMask === value) {
  8927. return;
  8928. }
  8929. this._depthMask = value;
  8930. this._isDepthMaskDirty = true;
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8936. get: function () {
  8937. return this._depthTest;
  8938. },
  8939. set: function (value) {
  8940. if (this._depthTest === value) {
  8941. return;
  8942. }
  8943. this._depthTest = value;
  8944. this._isDepthTestDirty = true;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8950. get: function () {
  8951. return this._frontFace;
  8952. },
  8953. set: function (value) {
  8954. if (this._frontFace === value) {
  8955. return;
  8956. }
  8957. this._frontFace = value;
  8958. this._isFrontFaceDirty = true;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. _DepthCullingState.prototype.reset = function () {
  8964. this._depthMask = true;
  8965. this._depthTest = true;
  8966. this._depthFunc = null;
  8967. this._cullFace = null;
  8968. this._cull = null;
  8969. this._zOffset = 0;
  8970. this._frontFace = null;
  8971. this._isDepthTestDirty = true;
  8972. this._isDepthMaskDirty = true;
  8973. this._isDepthFuncDirty = false;
  8974. this._isCullFaceDirty = false;
  8975. this._isCullDirty = false;
  8976. this._isZOffsetDirty = false;
  8977. this._isFrontFaceDirty = false;
  8978. };
  8979. _DepthCullingState.prototype.apply = function (gl) {
  8980. if (!this.isDirty) {
  8981. return;
  8982. }
  8983. // Cull
  8984. if (this._isCullDirty) {
  8985. if (this.cull) {
  8986. gl.enable(gl.CULL_FACE);
  8987. }
  8988. else {
  8989. gl.disable(gl.CULL_FACE);
  8990. }
  8991. this._isCullDirty = false;
  8992. }
  8993. // Cull face
  8994. if (this._isCullFaceDirty) {
  8995. gl.cullFace(this.cullFace);
  8996. this._isCullFaceDirty = false;
  8997. }
  8998. // Depth mask
  8999. if (this._isDepthMaskDirty) {
  9000. gl.depthMask(this.depthMask);
  9001. this._isDepthMaskDirty = false;
  9002. }
  9003. // Depth test
  9004. if (this._isDepthTestDirty) {
  9005. if (this.depthTest) {
  9006. gl.enable(gl.DEPTH_TEST);
  9007. }
  9008. else {
  9009. gl.disable(gl.DEPTH_TEST);
  9010. }
  9011. this._isDepthTestDirty = false;
  9012. }
  9013. // Depth func
  9014. if (this._isDepthFuncDirty) {
  9015. gl.depthFunc(this.depthFunc);
  9016. this._isDepthFuncDirty = false;
  9017. }
  9018. // zOffset
  9019. if (this._isZOffsetDirty) {
  9020. if (this.zOffset) {
  9021. gl.enable(gl.POLYGON_OFFSET_FILL);
  9022. gl.polygonOffset(this.zOffset, 0);
  9023. }
  9024. else {
  9025. gl.disable(gl.POLYGON_OFFSET_FILL);
  9026. }
  9027. this._isZOffsetDirty = false;
  9028. }
  9029. // Front face
  9030. if (this._isFrontFaceDirty) {
  9031. gl.frontFace(this.frontFace);
  9032. this._isFrontFaceDirty = false;
  9033. }
  9034. };
  9035. return _DepthCullingState;
  9036. }());
  9037. BABYLON._DepthCullingState = _DepthCullingState;
  9038. })(BABYLON || (BABYLON = {}));
  9039. //# sourceMappingURL=babylon.depthCullingState.js.map
  9040. var BABYLON;
  9041. (function (BABYLON) {
  9042. var _StencilState = /** @class */ (function () {
  9043. function _StencilState() {
  9044. this._isStencilTestDirty = false;
  9045. this._isStencilMaskDirty = false;
  9046. this._isStencilFuncDirty = false;
  9047. this._isStencilOpDirty = false;
  9048. this.reset();
  9049. }
  9050. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9051. get: function () {
  9052. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9053. },
  9054. enumerable: true,
  9055. configurable: true
  9056. });
  9057. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9058. get: function () {
  9059. return this._stencilFunc;
  9060. },
  9061. set: function (value) {
  9062. if (this._stencilFunc === value) {
  9063. return;
  9064. }
  9065. this._stencilFunc = value;
  9066. this._isStencilFuncDirty = true;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9072. get: function () {
  9073. return this._stencilFuncRef;
  9074. },
  9075. set: function (value) {
  9076. if (this._stencilFuncRef === value) {
  9077. return;
  9078. }
  9079. this._stencilFuncRef = value;
  9080. this._isStencilFuncDirty = true;
  9081. },
  9082. enumerable: true,
  9083. configurable: true
  9084. });
  9085. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9086. get: function () {
  9087. return this._stencilFuncMask;
  9088. },
  9089. set: function (value) {
  9090. if (this._stencilFuncMask === value) {
  9091. return;
  9092. }
  9093. this._stencilFuncMask = value;
  9094. this._isStencilFuncDirty = true;
  9095. },
  9096. enumerable: true,
  9097. configurable: true
  9098. });
  9099. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9100. get: function () {
  9101. return this._stencilOpStencilFail;
  9102. },
  9103. set: function (value) {
  9104. if (this._stencilOpStencilFail === value) {
  9105. return;
  9106. }
  9107. this._stencilOpStencilFail = value;
  9108. this._isStencilOpDirty = true;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9114. get: function () {
  9115. return this._stencilOpDepthFail;
  9116. },
  9117. set: function (value) {
  9118. if (this._stencilOpDepthFail === value) {
  9119. return;
  9120. }
  9121. this._stencilOpDepthFail = value;
  9122. this._isStencilOpDirty = true;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9128. get: function () {
  9129. return this._stencilOpStencilDepthPass;
  9130. },
  9131. set: function (value) {
  9132. if (this._stencilOpStencilDepthPass === value) {
  9133. return;
  9134. }
  9135. this._stencilOpStencilDepthPass = value;
  9136. this._isStencilOpDirty = true;
  9137. },
  9138. enumerable: true,
  9139. configurable: true
  9140. });
  9141. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9142. get: function () {
  9143. return this._stencilMask;
  9144. },
  9145. set: function (value) {
  9146. if (this._stencilMask === value) {
  9147. return;
  9148. }
  9149. this._stencilMask = value;
  9150. this._isStencilMaskDirty = true;
  9151. },
  9152. enumerable: true,
  9153. configurable: true
  9154. });
  9155. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9156. get: function () {
  9157. return this._stencilTest;
  9158. },
  9159. set: function (value) {
  9160. if (this._stencilTest === value) {
  9161. return;
  9162. }
  9163. this._stencilTest = value;
  9164. this._isStencilTestDirty = true;
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. _StencilState.prototype.reset = function () {
  9170. this._stencilTest = false;
  9171. this._stencilMask = 0xFF;
  9172. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9173. this._stencilFuncRef = 1;
  9174. this._stencilFuncMask = 0xFF;
  9175. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9176. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9177. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9178. this._isStencilTestDirty = true;
  9179. this._isStencilMaskDirty = true;
  9180. this._isStencilFuncDirty = true;
  9181. this._isStencilOpDirty = true;
  9182. };
  9183. _StencilState.prototype.apply = function (gl) {
  9184. if (!this.isDirty) {
  9185. return;
  9186. }
  9187. // Stencil test
  9188. if (this._isStencilTestDirty) {
  9189. if (this.stencilTest) {
  9190. gl.enable(gl.STENCIL_TEST);
  9191. }
  9192. else {
  9193. gl.disable(gl.STENCIL_TEST);
  9194. }
  9195. this._isStencilTestDirty = false;
  9196. }
  9197. // Stencil mask
  9198. if (this._isStencilMaskDirty) {
  9199. gl.stencilMask(this.stencilMask);
  9200. this._isStencilMaskDirty = false;
  9201. }
  9202. // Stencil func
  9203. if (this._isStencilFuncDirty) {
  9204. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9205. this._isStencilFuncDirty = false;
  9206. }
  9207. // Stencil op
  9208. if (this._isStencilOpDirty) {
  9209. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9210. this._isStencilOpDirty = false;
  9211. }
  9212. };
  9213. return _StencilState;
  9214. }());
  9215. BABYLON._StencilState = _StencilState;
  9216. })(BABYLON || (BABYLON = {}));
  9217. //# sourceMappingURL=babylon.stencilState.js.map
  9218. var BABYLON;
  9219. (function (BABYLON) {
  9220. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9221. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9222. };
  9223. var compileRawShader = function (gl, source, type) {
  9224. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9225. gl.shaderSource(shader, source);
  9226. gl.compileShader(shader);
  9227. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9228. var log = gl.getShaderInfoLog(shader);
  9229. if (log) {
  9230. throw new Error(log);
  9231. }
  9232. }
  9233. if (!shader) {
  9234. throw new Error("Something went wrong while compile the shader.");
  9235. }
  9236. return shader;
  9237. };
  9238. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9239. var magFilter = gl.NEAREST;
  9240. var minFilter = gl.NEAREST;
  9241. switch (samplingMode) {
  9242. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9243. magFilter = gl.LINEAR;
  9244. if (generateMipMaps) {
  9245. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9246. }
  9247. else {
  9248. minFilter = gl.LINEAR;
  9249. }
  9250. break;
  9251. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9252. magFilter = gl.LINEAR;
  9253. if (generateMipMaps) {
  9254. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9255. }
  9256. else {
  9257. minFilter = gl.LINEAR;
  9258. }
  9259. break;
  9260. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9261. magFilter = gl.NEAREST;
  9262. if (generateMipMaps) {
  9263. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9264. }
  9265. else {
  9266. minFilter = gl.NEAREST;
  9267. }
  9268. break;
  9269. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9270. magFilter = gl.NEAREST;
  9271. if (generateMipMaps) {
  9272. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9273. }
  9274. else {
  9275. minFilter = gl.NEAREST;
  9276. }
  9277. break;
  9278. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9279. magFilter = gl.NEAREST;
  9280. if (generateMipMaps) {
  9281. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9282. }
  9283. else {
  9284. minFilter = gl.LINEAR;
  9285. }
  9286. break;
  9287. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9288. magFilter = gl.NEAREST;
  9289. if (generateMipMaps) {
  9290. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9291. }
  9292. else {
  9293. minFilter = gl.LINEAR;
  9294. }
  9295. break;
  9296. case BABYLON.Texture.NEAREST_LINEAR:
  9297. magFilter = gl.NEAREST;
  9298. minFilter = gl.LINEAR;
  9299. break;
  9300. case BABYLON.Texture.NEAREST_NEAREST:
  9301. magFilter = gl.NEAREST;
  9302. minFilter = gl.NEAREST;
  9303. break;
  9304. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9305. magFilter = gl.LINEAR;
  9306. if (generateMipMaps) {
  9307. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9308. }
  9309. else {
  9310. minFilter = gl.NEAREST;
  9311. }
  9312. break;
  9313. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9314. magFilter = gl.LINEAR;
  9315. if (generateMipMaps) {
  9316. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9317. }
  9318. else {
  9319. minFilter = gl.NEAREST;
  9320. }
  9321. break;
  9322. case BABYLON.Texture.LINEAR_LINEAR:
  9323. magFilter = gl.LINEAR;
  9324. minFilter = gl.LINEAR;
  9325. break;
  9326. case BABYLON.Texture.LINEAR_NEAREST:
  9327. magFilter = gl.LINEAR;
  9328. minFilter = gl.NEAREST;
  9329. break;
  9330. }
  9331. return {
  9332. min: minFilter,
  9333. mag: magFilter
  9334. };
  9335. };
  9336. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9337. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9338. var img;
  9339. var onload = function () {
  9340. loadedImages[index] = img;
  9341. loadedImages._internalCount++;
  9342. if (scene) {
  9343. scene._removePendingData(img);
  9344. }
  9345. if (loadedImages._internalCount === 6) {
  9346. onfinish(loadedImages);
  9347. }
  9348. };
  9349. var onerror = function (message, exception) {
  9350. if (scene) {
  9351. scene._removePendingData(img);
  9352. }
  9353. if (onErrorCallBack) {
  9354. onErrorCallBack(message, exception);
  9355. }
  9356. };
  9357. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9358. if (scene) {
  9359. scene._addPendingData(img);
  9360. }
  9361. };
  9362. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9363. if (onError === void 0) { onError = null; }
  9364. var loadedImages = [];
  9365. loadedImages._internalCount = 0;
  9366. for (var index = 0; index < 6; index++) {
  9367. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9368. }
  9369. };
  9370. var BufferPointer = /** @class */ (function () {
  9371. function BufferPointer() {
  9372. }
  9373. return BufferPointer;
  9374. }());
  9375. var InstancingAttributeInfo = /** @class */ (function () {
  9376. function InstancingAttributeInfo() {
  9377. }
  9378. return InstancingAttributeInfo;
  9379. }());
  9380. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9381. /**
  9382. * Define options used to create a render target texture
  9383. */
  9384. var RenderTargetCreationOptions = /** @class */ (function () {
  9385. function RenderTargetCreationOptions() {
  9386. }
  9387. return RenderTargetCreationOptions;
  9388. }());
  9389. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9390. /**
  9391. * Regroup several parameters relative to the browser in use
  9392. */
  9393. var EngineCapabilities = /** @class */ (function () {
  9394. function EngineCapabilities() {
  9395. }
  9396. return EngineCapabilities;
  9397. }());
  9398. BABYLON.EngineCapabilities = EngineCapabilities;
  9399. /**
  9400. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9401. */
  9402. var Engine = /** @class */ (function () {
  9403. /**
  9404. * @constructor
  9405. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9406. * @param antialias defines enable antialiasing (default: false)
  9407. * @param options defines further options to be sent to the getContext() function
  9408. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9409. */
  9410. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9411. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9412. var _this = this;
  9413. // Public members
  9414. this.forcePOTTextures = false;
  9415. this.isFullscreen = false;
  9416. this.isPointerLock = false;
  9417. this.cullBackFaces = true;
  9418. this.renderEvenInBackground = true;
  9419. this.preventCacheWipeBetweenFrames = false;
  9420. // To enable/disable IDB support and avoid XHR on .manifest
  9421. this.enableOfflineSupport = false;
  9422. this.scenes = new Array();
  9423. this.postProcesses = new Array();
  9424. // Observables
  9425. /**
  9426. * Observable event triggered each time the rendering canvas is resized
  9427. */
  9428. this.onResizeObservable = new BABYLON.Observable();
  9429. /**
  9430. * Observable event triggered each time the canvas loses focus
  9431. */
  9432. this.onCanvasBlurObservable = new BABYLON.Observable();
  9433. /**
  9434. * Observable event triggered each time the canvas gains focus
  9435. */
  9436. this.onCanvasFocusObservable = new BABYLON.Observable();
  9437. /**
  9438. * Observable event triggered each time the canvas receives pointerout event
  9439. */
  9440. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9441. /**
  9442. * Observable event triggered before each texture is initialized
  9443. */
  9444. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9445. //WebVR
  9446. this._vrDisplay = undefined;
  9447. this._vrSupported = false;
  9448. this._vrExclusivePointerMode = false;
  9449. // Uniform buffers list
  9450. this.disableUniformBuffers = false;
  9451. this._uniformBuffers = new Array();
  9452. // Observables
  9453. /**
  9454. * Observable raised when the engine begins a new frame
  9455. */
  9456. this.onBeginFrameObservable = new BABYLON.Observable();
  9457. /**
  9458. * Observable raised when the engine ends the current frame
  9459. */
  9460. this.onEndFrameObservable = new BABYLON.Observable();
  9461. /**
  9462. * Observable raised when the engine is about to compile a shader
  9463. */
  9464. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9465. /**
  9466. * Observable raised when the engine has jsut compiled a shader
  9467. */
  9468. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9469. this._windowIsBackground = false;
  9470. this._webGLVersion = 1.0;
  9471. this._badOS = false;
  9472. this._badDesktopOS = false;
  9473. /**
  9474. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9475. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9476. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9477. */
  9478. this.disableTextureBindingOptimization = false;
  9479. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9480. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9481. this.onVRRequestPresentStart = new BABYLON.Observable();
  9482. this._colorWrite = true;
  9483. this._drawCalls = new BABYLON.PerfCounter();
  9484. this._textureCollisions = new BABYLON.PerfCounter();
  9485. this._renderingQueueLaunched = false;
  9486. this._activeRenderLoops = new Array();
  9487. // Deterministic lockstepMaxSteps
  9488. this._deterministicLockstep = false;
  9489. this._lockstepMaxSteps = 4;
  9490. // Lost context
  9491. this.onContextLostObservable = new BABYLON.Observable();
  9492. this.onContextRestoredObservable = new BABYLON.Observable();
  9493. this._contextWasLost = false;
  9494. this._doNotHandleContextLost = false;
  9495. // FPS
  9496. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9497. this._fps = 60;
  9498. this._deltaTime = 0;
  9499. /**
  9500. * Turn this value on if you want to pause FPS computation when in background
  9501. */
  9502. this.disablePerformanceMonitorInBackground = false;
  9503. // States
  9504. this._depthCullingState = new BABYLON._DepthCullingState();
  9505. this._stencilState = new BABYLON._StencilState();
  9506. this._alphaState = new BABYLON._AlphaState();
  9507. this._alphaMode = Engine.ALPHA_DISABLE;
  9508. // Cache
  9509. this._internalTexturesCache = new Array();
  9510. this._activeChannel = 0;
  9511. this._currentTextureChannel = -1;
  9512. this._boundTexturesCache = {};
  9513. this._compiledEffects = {};
  9514. this._vertexAttribArraysEnabled = [];
  9515. this._uintIndicesCurrentlySet = false;
  9516. this._currentBoundBuffer = new Array();
  9517. this._currentBufferPointers = new Array();
  9518. this._currentInstanceLocations = new Array();
  9519. this._currentInstanceBuffers = new Array();
  9520. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9521. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9522. this._vaoRecordInProgress = false;
  9523. this._mustWipeVertexAttributes = false;
  9524. this._nextFreeTextureSlots = new Array();
  9525. this._maxSimultaneousTextures = 0;
  9526. this._activeRequests = new Array();
  9527. // Hardware supported Compressed Textures
  9528. this._texturesSupported = new Array();
  9529. this._onVRFullScreenTriggered = function () {
  9530. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9531. //get the old size before we change
  9532. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9533. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9534. //get the width and height, change the render size
  9535. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9536. _this.setHardwareScalingLevel(1);
  9537. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9538. }
  9539. else {
  9540. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9541. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9542. }
  9543. };
  9544. this._boundUniforms = {};
  9545. // Register promises
  9546. BABYLON.PromisePolyfill.Apply();
  9547. var canvas = null;
  9548. Engine.Instances.push(this);
  9549. if (!canvasOrContext) {
  9550. return;
  9551. }
  9552. options = options || {};
  9553. if (canvasOrContext.getContext) {
  9554. canvas = canvasOrContext;
  9555. this._renderingCanvas = canvas;
  9556. if (antialias != null) {
  9557. options.antialias = antialias;
  9558. }
  9559. if (options.deterministicLockstep === undefined) {
  9560. options.deterministicLockstep = false;
  9561. }
  9562. if (options.lockstepMaxSteps === undefined) {
  9563. options.lockstepMaxSteps = 4;
  9564. }
  9565. if (options.preserveDrawingBuffer === undefined) {
  9566. options.preserveDrawingBuffer = false;
  9567. }
  9568. if (options.audioEngine === undefined) {
  9569. options.audioEngine = true;
  9570. }
  9571. if (options.stencil === undefined) {
  9572. options.stencil = true;
  9573. }
  9574. this._deterministicLockstep = options.deterministicLockstep;
  9575. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9576. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9577. // Exceptions
  9578. if (navigator && navigator.userAgent) {
  9579. var ua = navigator.userAgent;
  9580. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9581. var exception = _a[_i];
  9582. var key = exception.key;
  9583. var targets = exception.targets;
  9584. if (ua.indexOf(key) > -1) {
  9585. if (exception.capture && exception.captureConstraint) {
  9586. var capture = exception.capture;
  9587. var constraint = exception.captureConstraint;
  9588. var regex = new RegExp(capture);
  9589. var matches = regex.exec(ua);
  9590. if (matches && matches.length > 0) {
  9591. var capturedValue = parseInt(matches[matches.length - 1]);
  9592. if (capturedValue >= constraint) {
  9593. continue;
  9594. }
  9595. }
  9596. }
  9597. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9598. var target = targets_1[_b];
  9599. switch (target) {
  9600. case "uniformBuffer":
  9601. this.disableUniformBuffers = true;
  9602. break;
  9603. case "textureBindingOptimization":
  9604. this.disableTextureBindingOptimization = true;
  9605. break;
  9606. }
  9607. }
  9608. break;
  9609. }
  9610. }
  9611. }
  9612. // GL
  9613. if (!options.disableWebGL2Support) {
  9614. try {
  9615. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9616. if (this._gl) {
  9617. this._webGLVersion = 2.0;
  9618. }
  9619. }
  9620. catch (e) {
  9621. // Do nothing
  9622. }
  9623. }
  9624. if (!this._gl) {
  9625. if (!canvas) {
  9626. throw new Error("The provided canvas is null or undefined.");
  9627. }
  9628. try {
  9629. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9630. }
  9631. catch (e) {
  9632. throw new Error("WebGL not supported");
  9633. }
  9634. }
  9635. if (!this._gl) {
  9636. throw new Error("WebGL not supported");
  9637. }
  9638. this._onCanvasFocus = function () {
  9639. _this.onCanvasFocusObservable.notifyObservers(_this);
  9640. };
  9641. this._onCanvasBlur = function () {
  9642. _this.onCanvasBlurObservable.notifyObservers(_this);
  9643. };
  9644. canvas.addEventListener("focus", this._onCanvasFocus);
  9645. canvas.addEventListener("blur", this._onCanvasBlur);
  9646. this._onBlur = function () {
  9647. if (_this.disablePerformanceMonitorInBackground) {
  9648. _this._performanceMonitor.disable();
  9649. }
  9650. _this._windowIsBackground = true;
  9651. };
  9652. this._onFocus = function () {
  9653. if (_this.disablePerformanceMonitorInBackground) {
  9654. _this._performanceMonitor.enable();
  9655. }
  9656. _this._windowIsBackground = false;
  9657. };
  9658. this._onCanvasPointerOut = function () {
  9659. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9660. };
  9661. window.addEventListener("blur", this._onBlur);
  9662. window.addEventListener("focus", this._onFocus);
  9663. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9664. // Context lost
  9665. if (!this._doNotHandleContextLost) {
  9666. this._onContextLost = function (evt) {
  9667. evt.preventDefault();
  9668. _this._contextWasLost = true;
  9669. BABYLON.Tools.Warn("WebGL context lost.");
  9670. _this.onContextLostObservable.notifyObservers(_this);
  9671. };
  9672. this._onContextRestored = function (evt) {
  9673. // Adding a timeout to avoid race condition at browser level
  9674. setTimeout(function () {
  9675. // Rebuild gl context
  9676. _this._initGLContext();
  9677. // Rebuild effects
  9678. _this._rebuildEffects();
  9679. // Rebuild textures
  9680. _this._rebuildInternalTextures();
  9681. // Rebuild buffers
  9682. _this._rebuildBuffers();
  9683. // Cache
  9684. _this.wipeCaches(true);
  9685. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9686. _this.onContextRestoredObservable.notifyObservers(_this);
  9687. _this._contextWasLost = false;
  9688. }, 0);
  9689. };
  9690. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9691. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9692. }
  9693. }
  9694. else {
  9695. this._gl = canvasOrContext;
  9696. this._renderingCanvas = this._gl.canvas;
  9697. if (this._gl.renderbufferStorageMultisample) {
  9698. this._webGLVersion = 2.0;
  9699. }
  9700. options.stencil = this._gl.getContextAttributes().stencil;
  9701. }
  9702. // Viewport
  9703. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9704. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9705. this.resize();
  9706. this._isStencilEnable = options.stencil ? true : false;
  9707. this._initGLContext();
  9708. if (canvas) {
  9709. // Fullscreen
  9710. this._onFullscreenChange = function () {
  9711. if (document.fullscreen !== undefined) {
  9712. _this.isFullscreen = document.fullscreen;
  9713. }
  9714. else if (document.mozFullScreen !== undefined) {
  9715. _this.isFullscreen = document.mozFullScreen;
  9716. }
  9717. else if (document.webkitIsFullScreen !== undefined) {
  9718. _this.isFullscreen = document.webkitIsFullScreen;
  9719. }
  9720. else if (document.msIsFullScreen !== undefined) {
  9721. _this.isFullscreen = document.msIsFullScreen;
  9722. }
  9723. // Pointer lock
  9724. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9725. canvas.requestPointerLock = canvas.requestPointerLock ||
  9726. canvas.msRequestPointerLock ||
  9727. canvas.mozRequestPointerLock ||
  9728. canvas.webkitRequestPointerLock;
  9729. if (canvas.requestPointerLock) {
  9730. canvas.requestPointerLock();
  9731. }
  9732. }
  9733. };
  9734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9738. // Pointer lock
  9739. this._onPointerLockChange = function () {
  9740. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9741. document.webkitPointerLockElement === canvas ||
  9742. document.msPointerLockElement === canvas ||
  9743. document.pointerLockElement === canvas);
  9744. };
  9745. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9746. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9747. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9748. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9749. this._onVRDisplayPointerRestricted = function () {
  9750. if (canvas) {
  9751. canvas.requestPointerLock();
  9752. }
  9753. };
  9754. this._onVRDisplayPointerUnrestricted = function () {
  9755. document.exitPointerLock();
  9756. };
  9757. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9758. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9759. }
  9760. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9761. Engine.audioEngine = new BABYLON.AudioEngine();
  9762. }
  9763. // Prepare buffer pointers
  9764. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9765. this._currentBufferPointers[i] = new BufferPointer();
  9766. }
  9767. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9768. // Load WebVR Devices
  9769. if (options.autoEnableWebVR) {
  9770. this.initWebVR();
  9771. }
  9772. // Detect if we are running on a faulty buggy OS.
  9773. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9774. // Detect if we are running on a faulty buggy desktop OS.
  9775. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9776. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9777. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9778. }
  9779. Object.defineProperty(Engine, "LastCreatedEngine", {
  9780. get: function () {
  9781. if (Engine.Instances.length === 0) {
  9782. return null;
  9783. }
  9784. return Engine.Instances[Engine.Instances.length - 1];
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Object.defineProperty(Engine, "LastCreatedScene", {
  9790. get: function () {
  9791. var lastCreatedEngine = Engine.LastCreatedEngine;
  9792. if (!lastCreatedEngine) {
  9793. return null;
  9794. }
  9795. if (lastCreatedEngine.scenes.length === 0) {
  9796. return null;
  9797. }
  9798. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. /**
  9804. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9805. */
  9806. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9807. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9808. var engine = Engine.Instances[engineIndex];
  9809. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9810. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9811. }
  9812. }
  9813. };
  9814. Object.defineProperty(Engine, "NEVER", {
  9815. get: function () {
  9816. return Engine._NEVER;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(Engine, "ALWAYS", {
  9822. get: function () {
  9823. return Engine._ALWAYS;
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(Engine, "LESS", {
  9829. get: function () {
  9830. return Engine._LESS;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(Engine, "EQUAL", {
  9836. get: function () {
  9837. return Engine._EQUAL;
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(Engine, "LEQUAL", {
  9843. get: function () {
  9844. return Engine._LEQUAL;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(Engine, "GREATER", {
  9850. get: function () {
  9851. return Engine._GREATER;
  9852. },
  9853. enumerable: true,
  9854. configurable: true
  9855. });
  9856. Object.defineProperty(Engine, "GEQUAL", {
  9857. get: function () {
  9858. return Engine._GEQUAL;
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(Engine, "NOTEQUAL", {
  9864. get: function () {
  9865. return Engine._NOTEQUAL;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Object.defineProperty(Engine, "KEEP", {
  9871. get: function () {
  9872. return Engine._KEEP;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Engine, "REPLACE", {
  9878. get: function () {
  9879. return Engine._REPLACE;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Engine, "INCR", {
  9885. get: function () {
  9886. return Engine._INCR;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Engine, "DECR", {
  9892. get: function () {
  9893. return Engine._DECR;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(Engine, "INVERT", {
  9899. get: function () {
  9900. return Engine._INVERT;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Engine, "INCR_WRAP", {
  9906. get: function () {
  9907. return Engine._INCR_WRAP;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(Engine, "DECR_WRAP", {
  9913. get: function () {
  9914. return Engine._DECR_WRAP;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9920. get: function () {
  9921. return Engine._ALPHA_DISABLE;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9927. get: function () {
  9928. return Engine._ALPHA_ONEONE;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(Engine, "ALPHA_ADD", {
  9934. get: function () {
  9935. return Engine._ALPHA_ADD;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9941. get: function () {
  9942. return Engine._ALPHA_COMBINE;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9948. get: function () {
  9949. return Engine._ALPHA_SUBTRACT;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9955. get: function () {
  9956. return Engine._ALPHA_MULTIPLY;
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9962. get: function () {
  9963. return Engine._ALPHA_MAXIMIZED;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9969. get: function () {
  9970. return Engine._ALPHA_PREMULTIPLIED;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9976. get: function () {
  9977. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9983. get: function () {
  9984. return Engine._ALPHA_INTERPOLATE;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9990. get: function () {
  9991. return Engine._ALPHA_SCREENMODE;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9997. get: function () {
  9998. return Engine._DELAYLOADSTATE_NONE;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10004. get: function () {
  10005. return Engine._DELAYLOADSTATE_LOADED;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10011. get: function () {
  10012. return Engine._DELAYLOADSTATE_LOADING;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10018. get: function () {
  10019. return Engine._DELAYLOADSTATE_NOTLOADED;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10025. get: function () {
  10026. return Engine._TEXTUREFORMAT_ALPHA;
  10027. },
  10028. enumerable: true,
  10029. configurable: true
  10030. });
  10031. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10032. get: function () {
  10033. return Engine._TEXTUREFORMAT_LUMINANCE;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10039. get: function () {
  10040. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10041. },
  10042. enumerable: true,
  10043. configurable: true
  10044. });
  10045. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10046. get: function () {
  10047. return Engine._TEXTUREFORMAT_RGB;
  10048. },
  10049. enumerable: true,
  10050. configurable: true
  10051. });
  10052. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10053. get: function () {
  10054. return Engine._TEXTUREFORMAT_RGBA;
  10055. },
  10056. enumerable: true,
  10057. configurable: true
  10058. });
  10059. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10060. get: function () {
  10061. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10067. get: function () {
  10068. return Engine._TEXTURETYPE_FLOAT;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10074. get: function () {
  10075. return Engine._TEXTURETYPE_HALF_FLOAT;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10081. get: function () {
  10082. return Engine._SCALEMODE_FLOOR;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10088. get: function () {
  10089. return Engine._SCALEMODE_NEAREST;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10095. get: function () {
  10096. return Engine._SCALEMODE_CEILING;
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Object.defineProperty(Engine, "Version", {
  10102. get: function () {
  10103. return "3.2.0-alpha6";
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10109. get: function () {
  10110. return this._vrExclusivePointerMode;
  10111. },
  10112. enumerable: true,
  10113. configurable: true
  10114. });
  10115. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10116. get: function () {
  10117. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10123. get: function () {
  10124. return this._webGLVersion < 2 || this.forcePOTTextures;
  10125. },
  10126. enumerable: true,
  10127. configurable: true
  10128. });
  10129. Object.defineProperty(Engine.prototype, "badOS", {
  10130. get: function () {
  10131. return this._badOS;
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10137. get: function () {
  10138. return this._badDesktopOS;
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10144. get: function () {
  10145. return this._performanceMonitor;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10151. get: function () {
  10152. return this._texturesSupported;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10158. get: function () {
  10159. return this._textureFormatInUse;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(Engine.prototype, "currentViewport", {
  10165. get: function () {
  10166. return this._cachedViewport;
  10167. },
  10168. enumerable: true,
  10169. configurable: true
  10170. });
  10171. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10172. // Empty texture
  10173. get: function () {
  10174. if (!this._emptyTexture) {
  10175. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10176. }
  10177. return this._emptyTexture;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10183. get: function () {
  10184. if (!this._emptyTexture3D) {
  10185. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10186. }
  10187. return this._emptyTexture3D;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10193. get: function () {
  10194. if (!this._emptyCubeTexture) {
  10195. var faceData = new Uint8Array(4);
  10196. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10197. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10198. }
  10199. return this._emptyCubeTexture;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Engine.prototype._rebuildInternalTextures = function () {
  10205. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10206. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10207. var internalTexture = currentState_1[_i];
  10208. internalTexture._rebuild();
  10209. }
  10210. };
  10211. Engine.prototype._rebuildEffects = function () {
  10212. for (var key in this._compiledEffects) {
  10213. var effect = this._compiledEffects[key];
  10214. effect._prepareEffect();
  10215. }
  10216. BABYLON.Effect.ResetCache();
  10217. };
  10218. Engine.prototype._rebuildBuffers = function () {
  10219. // Index / Vertex
  10220. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10221. var scene = _a[_i];
  10222. scene.resetCachedMaterial();
  10223. scene._rebuildGeometries();
  10224. scene._rebuildTextures();
  10225. }
  10226. // Uniforms
  10227. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10228. var uniformBuffer = _c[_b];
  10229. uniformBuffer._rebuild();
  10230. }
  10231. };
  10232. Engine.prototype._initGLContext = function () {
  10233. // Caps
  10234. this._caps = new EngineCapabilities();
  10235. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10236. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10237. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10238. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10239. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10240. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10241. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10242. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10243. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10244. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10245. // Infos
  10246. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10247. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10248. if (rendererInfo != null) {
  10249. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10250. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10251. }
  10252. if (!this._glVendor) {
  10253. this._glVendor = "Unknown vendor";
  10254. }
  10255. if (!this._glRenderer) {
  10256. this._glRenderer = "Unknown renderer";
  10257. }
  10258. // Constants
  10259. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10260. if (this._gl.RGBA16F !== 0x881A) {
  10261. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10262. }
  10263. if (this._gl.RGBA32F !== 0x8814) {
  10264. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10265. }
  10266. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10267. this._gl.DEPTH24_STENCIL8 = 35056;
  10268. }
  10269. // Extensions
  10270. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10271. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10272. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10273. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10274. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10275. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10276. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10277. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  10278. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10279. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10280. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10281. this._caps.highPrecisionShaderSupported = true;
  10282. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10283. if (this._caps.timerQuery) {
  10284. if (this._webGLVersion === 1) {
  10285. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10286. }
  10287. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10288. }
  10289. // Checks if some of the format renders first to allow the use of webgl inspector.
  10290. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10291. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10292. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10293. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10294. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10295. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10296. if (this._webGLVersion > 1) {
  10297. this._gl.HALF_FLOAT_OES = 0x140B;
  10298. }
  10299. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10300. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10301. // Draw buffers
  10302. if (this._webGLVersion > 1) {
  10303. this._caps.drawBuffersExtension = true;
  10304. }
  10305. else {
  10306. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10307. if (drawBuffersExtension !== null) {
  10308. this._caps.drawBuffersExtension = true;
  10309. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10310. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10311. for (var i = 0; i < 16; i++) {
  10312. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10313. }
  10314. }
  10315. else {
  10316. this._caps.drawBuffersExtension = false;
  10317. }
  10318. }
  10319. // Depth Texture
  10320. if (this._webGLVersion > 1) {
  10321. this._caps.depthTextureExtension = true;
  10322. }
  10323. else {
  10324. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10325. if (depthTextureExtension != null) {
  10326. this._caps.depthTextureExtension = true;
  10327. }
  10328. }
  10329. // Vertex array object
  10330. if (this._webGLVersion > 1) {
  10331. this._caps.vertexArrayObject = true;
  10332. }
  10333. else {
  10334. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10335. if (vertexArrayObjectExtension != null) {
  10336. this._caps.vertexArrayObject = true;
  10337. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10338. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10339. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10340. }
  10341. else {
  10342. this._caps.vertexArrayObject = false;
  10343. }
  10344. }
  10345. // Instances count
  10346. if (this._webGLVersion > 1) {
  10347. this._caps.instancedArrays = true;
  10348. }
  10349. else {
  10350. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10351. if (instanceExtension != null) {
  10352. this._caps.instancedArrays = true;
  10353. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10354. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10355. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10356. }
  10357. else {
  10358. this._caps.instancedArrays = false;
  10359. }
  10360. }
  10361. // Intelligently add supported compressed formats in order to check for.
  10362. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10363. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10364. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10365. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10366. if (this._caps.astc)
  10367. this.texturesSupported.push('-astc.ktx');
  10368. if (this._caps.s3tc)
  10369. this.texturesSupported.push('-dxt.ktx');
  10370. if (this._caps.pvrtc)
  10371. this.texturesSupported.push('-pvrtc.ktx');
  10372. if (this._caps.etc2)
  10373. this.texturesSupported.push('-etc2.ktx');
  10374. if (this._caps.etc1)
  10375. this.texturesSupported.push('-etc1.ktx');
  10376. if (this._gl.getShaderPrecisionFormat) {
  10377. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10378. if (highp) {
  10379. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10380. }
  10381. }
  10382. // Depth buffer
  10383. this.setDepthBuffer(true);
  10384. this.setDepthFunctionToLessOrEqual();
  10385. this.setDepthWrite(true);
  10386. // Texture maps
  10387. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10388. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10389. this._nextFreeTextureSlots.push(slot);
  10390. }
  10391. };
  10392. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10393. get: function () {
  10394. return this._webGLVersion;
  10395. },
  10396. enumerable: true,
  10397. configurable: true
  10398. });
  10399. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10400. /**
  10401. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10402. */
  10403. get: function () {
  10404. return this._isStencilEnable;
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Engine.prototype._prepareWorkingCanvas = function () {
  10410. if (this._workingCanvas) {
  10411. return;
  10412. }
  10413. this._workingCanvas = document.createElement("canvas");
  10414. var context = this._workingCanvas.getContext("2d");
  10415. if (context) {
  10416. this._workingContext = context;
  10417. }
  10418. };
  10419. Engine.prototype.resetTextureCache = function () {
  10420. for (var key in this._boundTexturesCache) {
  10421. var boundTexture = this._boundTexturesCache[key];
  10422. if (boundTexture) {
  10423. this._removeDesignatedSlot(boundTexture);
  10424. }
  10425. this._boundTexturesCache[key] = null;
  10426. }
  10427. if (!this.disableTextureBindingOptimization) {
  10428. this._nextFreeTextureSlots = [];
  10429. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10430. this._nextFreeTextureSlots.push(slot);
  10431. }
  10432. }
  10433. this._currentTextureChannel = -1;
  10434. };
  10435. Engine.prototype.isDeterministicLockStep = function () {
  10436. return this._deterministicLockstep;
  10437. };
  10438. Engine.prototype.getLockstepMaxSteps = function () {
  10439. return this._lockstepMaxSteps;
  10440. };
  10441. Engine.prototype.getGlInfo = function () {
  10442. return {
  10443. vendor: this._glVendor,
  10444. renderer: this._glRenderer,
  10445. version: this._glVersion
  10446. };
  10447. };
  10448. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10449. if (useScreen === void 0) { useScreen = false; }
  10450. var viewport = camera.viewport;
  10451. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10452. };
  10453. Engine.prototype.getRenderWidth = function (useScreen) {
  10454. if (useScreen === void 0) { useScreen = false; }
  10455. if (!useScreen && this._currentRenderTarget) {
  10456. return this._currentRenderTarget.width;
  10457. }
  10458. return this._gl.drawingBufferWidth;
  10459. };
  10460. Engine.prototype.getRenderHeight = function (useScreen) {
  10461. if (useScreen === void 0) { useScreen = false; }
  10462. if (!useScreen && this._currentRenderTarget) {
  10463. return this._currentRenderTarget.height;
  10464. }
  10465. return this._gl.drawingBufferHeight;
  10466. };
  10467. Engine.prototype.getRenderingCanvas = function () {
  10468. return this._renderingCanvas;
  10469. };
  10470. Engine.prototype.getRenderingCanvasClientRect = function () {
  10471. if (!this._renderingCanvas) {
  10472. return null;
  10473. }
  10474. return this._renderingCanvas.getBoundingClientRect();
  10475. };
  10476. Engine.prototype.setHardwareScalingLevel = function (level) {
  10477. this._hardwareScalingLevel = level;
  10478. this.resize();
  10479. };
  10480. Engine.prototype.getHardwareScalingLevel = function () {
  10481. return this._hardwareScalingLevel;
  10482. };
  10483. Engine.prototype.getLoadedTexturesCache = function () {
  10484. return this._internalTexturesCache;
  10485. };
  10486. Engine.prototype.getCaps = function () {
  10487. return this._caps;
  10488. };
  10489. Object.defineProperty(Engine.prototype, "drawCalls", {
  10490. /** The number of draw calls submitted last frame */
  10491. get: function () {
  10492. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10493. return 0;
  10494. },
  10495. enumerable: true,
  10496. configurable: true
  10497. });
  10498. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10499. get: function () {
  10500. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10501. return null;
  10502. },
  10503. enumerable: true,
  10504. configurable: true
  10505. });
  10506. Engine.prototype.getDepthFunction = function () {
  10507. return this._depthCullingState.depthFunc;
  10508. };
  10509. Engine.prototype.setDepthFunction = function (depthFunc) {
  10510. this._depthCullingState.depthFunc = depthFunc;
  10511. };
  10512. Engine.prototype.setDepthFunctionToGreater = function () {
  10513. this._depthCullingState.depthFunc = this._gl.GREATER;
  10514. };
  10515. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10516. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10517. };
  10518. Engine.prototype.setDepthFunctionToLess = function () {
  10519. this._depthCullingState.depthFunc = this._gl.LESS;
  10520. };
  10521. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10522. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10523. };
  10524. Engine.prototype.getStencilBuffer = function () {
  10525. return this._stencilState.stencilTest;
  10526. };
  10527. Engine.prototype.setStencilBuffer = function (enable) {
  10528. this._stencilState.stencilTest = enable;
  10529. };
  10530. Engine.prototype.getStencilMask = function () {
  10531. return this._stencilState.stencilMask;
  10532. };
  10533. Engine.prototype.setStencilMask = function (mask) {
  10534. this._stencilState.stencilMask = mask;
  10535. };
  10536. Engine.prototype.getStencilFunction = function () {
  10537. return this._stencilState.stencilFunc;
  10538. };
  10539. Engine.prototype.getStencilFunctionReference = function () {
  10540. return this._stencilState.stencilFuncRef;
  10541. };
  10542. Engine.prototype.getStencilFunctionMask = function () {
  10543. return this._stencilState.stencilFuncMask;
  10544. };
  10545. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10546. this._stencilState.stencilFunc = stencilFunc;
  10547. };
  10548. Engine.prototype.setStencilFunctionReference = function (reference) {
  10549. this._stencilState.stencilFuncRef = reference;
  10550. };
  10551. Engine.prototype.setStencilFunctionMask = function (mask) {
  10552. this._stencilState.stencilFuncMask = mask;
  10553. };
  10554. Engine.prototype.getStencilOperationFail = function () {
  10555. return this._stencilState.stencilOpStencilFail;
  10556. };
  10557. Engine.prototype.getStencilOperationDepthFail = function () {
  10558. return this._stencilState.stencilOpDepthFail;
  10559. };
  10560. Engine.prototype.getStencilOperationPass = function () {
  10561. return this._stencilState.stencilOpStencilDepthPass;
  10562. };
  10563. Engine.prototype.setStencilOperationFail = function (operation) {
  10564. this._stencilState.stencilOpStencilFail = operation;
  10565. };
  10566. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10567. this._stencilState.stencilOpDepthFail = operation;
  10568. };
  10569. Engine.prototype.setStencilOperationPass = function (operation) {
  10570. this._stencilState.stencilOpStencilDepthPass = operation;
  10571. };
  10572. Engine.prototype.setDitheringState = function (value) {
  10573. if (value) {
  10574. this._gl.enable(this._gl.DITHER);
  10575. }
  10576. else {
  10577. this._gl.disable(this._gl.DITHER);
  10578. }
  10579. };
  10580. Engine.prototype.setRasterizerState = function (value) {
  10581. if (value) {
  10582. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10583. }
  10584. else {
  10585. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10586. }
  10587. };
  10588. /**
  10589. * stop executing a render loop function and remove it from the execution array
  10590. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10591. */
  10592. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10593. if (!renderFunction) {
  10594. this._activeRenderLoops = [];
  10595. return;
  10596. }
  10597. var index = this._activeRenderLoops.indexOf(renderFunction);
  10598. if (index >= 0) {
  10599. this._activeRenderLoops.splice(index, 1);
  10600. }
  10601. };
  10602. Engine.prototype._renderLoop = function () {
  10603. if (!this._contextWasLost) {
  10604. var shouldRender = true;
  10605. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10606. shouldRender = false;
  10607. }
  10608. if (shouldRender) {
  10609. // Start new frame
  10610. this.beginFrame();
  10611. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10612. var renderFunction = this._activeRenderLoops[index];
  10613. renderFunction();
  10614. }
  10615. // Present
  10616. this.endFrame();
  10617. }
  10618. }
  10619. if (this._activeRenderLoops.length > 0) {
  10620. // Register new frame
  10621. var requester = null;
  10622. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10623. requester = this._vrDisplay;
  10624. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10625. }
  10626. else {
  10627. this._renderingQueueLaunched = false;
  10628. }
  10629. };
  10630. /**
  10631. * Register and execute a render loop. The engine can have more than one render function.
  10632. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10633. * @example
  10634. * engine.runRenderLoop(function () {
  10635. * scene.render()
  10636. * })
  10637. */
  10638. Engine.prototype.runRenderLoop = function (renderFunction) {
  10639. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10640. return;
  10641. }
  10642. this._activeRenderLoops.push(renderFunction);
  10643. if (!this._renderingQueueLaunched) {
  10644. this._renderingQueueLaunched = true;
  10645. this._bindedRenderFunction = this._renderLoop.bind(this);
  10646. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10647. }
  10648. };
  10649. /**
  10650. * Toggle full screen mode.
  10651. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10652. * @param {any} options - an options object to be sent to the requestFullscreen function
  10653. */
  10654. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10655. if (this.isFullscreen) {
  10656. BABYLON.Tools.ExitFullscreen();
  10657. }
  10658. else {
  10659. this._pointerLockRequested = requestPointerLock;
  10660. if (this._renderingCanvas) {
  10661. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10662. }
  10663. }
  10664. };
  10665. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10666. if (stencil === void 0) { stencil = false; }
  10667. this.applyStates();
  10668. var mode = 0;
  10669. if (backBuffer && color) {
  10670. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10671. mode |= this._gl.COLOR_BUFFER_BIT;
  10672. }
  10673. if (depth) {
  10674. this._gl.clearDepth(1.0);
  10675. mode |= this._gl.DEPTH_BUFFER_BIT;
  10676. }
  10677. if (stencil) {
  10678. this._gl.clearStencil(0);
  10679. mode |= this._gl.STENCIL_BUFFER_BIT;
  10680. }
  10681. this._gl.clear(mode);
  10682. };
  10683. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10684. var gl = this._gl;
  10685. // Save state
  10686. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10687. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10688. // Change state
  10689. gl.enable(gl.SCISSOR_TEST);
  10690. gl.scissor(x, y, width, height);
  10691. // Clear
  10692. this.clear(clearColor, true, true, true);
  10693. // Restore state
  10694. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10695. if (curScissor === true) {
  10696. gl.enable(gl.SCISSOR_TEST);
  10697. }
  10698. else {
  10699. gl.disable(gl.SCISSOR_TEST);
  10700. }
  10701. };
  10702. /**
  10703. * Set the WebGL's viewport
  10704. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10705. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10706. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10707. */
  10708. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10709. var width = requiredWidth || this.getRenderWidth();
  10710. var height = requiredHeight || this.getRenderHeight();
  10711. var x = viewport.x || 0;
  10712. var y = viewport.y || 0;
  10713. this._cachedViewport = viewport;
  10714. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10715. };
  10716. /**
  10717. * Directly set the WebGL Viewport
  10718. * The x, y, width & height are directly passed to the WebGL call
  10719. * @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.
  10720. */
  10721. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10722. var currentViewport = this._cachedViewport;
  10723. this._cachedViewport = null;
  10724. this._gl.viewport(x, y, width, height);
  10725. return currentViewport;
  10726. };
  10727. Engine.prototype.beginFrame = function () {
  10728. this.onBeginFrameObservable.notifyObservers(this);
  10729. this._measureFps();
  10730. };
  10731. Engine.prototype.endFrame = function () {
  10732. //force a flush in case we are using a bad OS.
  10733. if (this._badOS) {
  10734. this.flushFramebuffer();
  10735. }
  10736. //submit frame to the vr device, if enabled
  10737. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10738. // TODO: We should only submit the frame if we read frameData successfully.
  10739. this._vrDisplay.submitFrame();
  10740. }
  10741. this.onEndFrameObservable.notifyObservers(this);
  10742. };
  10743. /**
  10744. * resize the view according to the canvas' size.
  10745. * @example
  10746. * window.addEventListener("resize", function () {
  10747. * engine.resize();
  10748. * });
  10749. */
  10750. Engine.prototype.resize = function () {
  10751. // We're not resizing the size of the canvas while in VR mode & presenting
  10752. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10753. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10754. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10755. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10756. }
  10757. };
  10758. /**
  10759. * force a specific size of the canvas
  10760. * @param {number} width - the new canvas' width
  10761. * @param {number} height - the new canvas' height
  10762. */
  10763. Engine.prototype.setSize = function (width, height) {
  10764. if (!this._renderingCanvas) {
  10765. return;
  10766. }
  10767. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10768. return;
  10769. }
  10770. this._renderingCanvas.width = width;
  10771. this._renderingCanvas.height = height;
  10772. for (var index = 0; index < this.scenes.length; index++) {
  10773. var scene = this.scenes[index];
  10774. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10775. var cam = scene.cameras[camIndex];
  10776. cam._currentRenderId = 0;
  10777. }
  10778. }
  10779. if (this.onResizeObservable.hasObservers) {
  10780. this.onResizeObservable.notifyObservers(this);
  10781. }
  10782. };
  10783. // WebVR functions
  10784. Engine.prototype.isVRDevicePresent = function () {
  10785. return !!this._vrDisplay;
  10786. };
  10787. Engine.prototype.getVRDevice = function () {
  10788. return this._vrDisplay;
  10789. };
  10790. Engine.prototype.initWebVR = function () {
  10791. var _this = this;
  10792. var notifyObservers = function () {
  10793. var eventArgs = {
  10794. vrDisplay: _this._vrDisplay,
  10795. vrSupported: _this._vrSupported
  10796. };
  10797. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10798. };
  10799. if (!this._onVrDisplayConnect) {
  10800. this._onVrDisplayConnect = function (event) {
  10801. _this._vrDisplay = event.display;
  10802. notifyObservers();
  10803. };
  10804. this._onVrDisplayDisconnect = function () {
  10805. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10806. _this._vrDisplay = undefined;
  10807. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10808. notifyObservers();
  10809. };
  10810. this._onVrDisplayPresentChange = function () {
  10811. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10812. };
  10813. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10814. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10815. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10816. }
  10817. this._getVRDisplays(notifyObservers);
  10818. return this.onVRDisplayChangedObservable;
  10819. };
  10820. Engine.prototype.enableVR = function () {
  10821. var _this = this;
  10822. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10823. var onResolved = function () {
  10824. _this.onVRRequestPresentComplete.notifyObservers(true);
  10825. _this._onVRFullScreenTriggered();
  10826. };
  10827. var onRejected = function () {
  10828. _this.onVRRequestPresentComplete.notifyObservers(false);
  10829. };
  10830. this.onVRRequestPresentStart.notifyObservers(this);
  10831. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10832. }
  10833. };
  10834. Engine.prototype.disableVR = function () {
  10835. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10836. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10837. }
  10838. };
  10839. Engine.prototype._getVRDisplays = function (callback) {
  10840. var _this = this;
  10841. var getWebVRDevices = function (devices) {
  10842. _this._vrSupported = true;
  10843. // note that devices may actually be an empty array. This is fine;
  10844. // we expect this._vrDisplay to be undefined in this case.
  10845. return _this._vrDisplay = devices[0];
  10846. };
  10847. if (navigator.getVRDisplays) {
  10848. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10849. // TODO: System CANNOT support WebVR, despite API presence.
  10850. _this._vrSupported = false;
  10851. callback();
  10852. });
  10853. }
  10854. else {
  10855. // TODO: Browser does not support WebVR
  10856. this._vrDisplay = undefined;
  10857. this._vrSupported = false;
  10858. callback();
  10859. }
  10860. };
  10861. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10862. if (this._currentRenderTarget) {
  10863. this.unBindFramebuffer(this._currentRenderTarget);
  10864. }
  10865. this._currentRenderTarget = texture;
  10866. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10867. var gl = this._gl;
  10868. if (texture.isCube) {
  10869. if (faceIndex === undefined) {
  10870. faceIndex = 0;
  10871. }
  10872. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10873. }
  10874. if (this._cachedViewport && !forceFullscreenViewport) {
  10875. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10876. }
  10877. else {
  10878. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10879. }
  10880. this.wipeCaches();
  10881. };
  10882. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10883. if (this._currentFramebuffer !== framebuffer) {
  10884. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10885. this._currentFramebuffer = framebuffer;
  10886. }
  10887. };
  10888. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10889. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10890. this._currentRenderTarget = null;
  10891. // If MSAA, we need to bitblt back to main texture
  10892. var gl = this._gl;
  10893. if (texture._MSAAFramebuffer) {
  10894. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10895. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10896. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10897. }
  10898. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10899. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10900. gl.generateMipmap(gl.TEXTURE_2D);
  10901. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10902. }
  10903. if (onBeforeUnbind) {
  10904. if (texture._MSAAFramebuffer) {
  10905. // Bind the correct framebuffer
  10906. this.bindUnboundFramebuffer(texture._framebuffer);
  10907. }
  10908. onBeforeUnbind();
  10909. }
  10910. this.bindUnboundFramebuffer(null);
  10911. };
  10912. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10913. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10914. this._currentRenderTarget = null;
  10915. // If MSAA, we need to bitblt back to main texture
  10916. var gl = this._gl;
  10917. if (textures[0]._MSAAFramebuffer) {
  10918. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10919. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10920. var attachments = textures[0]._attachments;
  10921. if (!attachments) {
  10922. attachments = new Array(textures.length);
  10923. textures[0]._attachments = attachments;
  10924. }
  10925. for (var i = 0; i < textures.length; i++) {
  10926. var texture = textures[i];
  10927. for (var j = 0; j < attachments.length; j++) {
  10928. attachments[j] = gl.NONE;
  10929. }
  10930. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10931. gl.readBuffer(attachments[i]);
  10932. gl.drawBuffers(attachments);
  10933. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10934. }
  10935. for (var i = 0; i < attachments.length; i++) {
  10936. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10937. }
  10938. gl.drawBuffers(attachments);
  10939. }
  10940. for (var i = 0; i < textures.length; i++) {
  10941. var texture = textures[i];
  10942. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10943. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10944. gl.generateMipmap(gl.TEXTURE_2D);
  10945. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10946. }
  10947. }
  10948. if (onBeforeUnbind) {
  10949. if (textures[0]._MSAAFramebuffer) {
  10950. // Bind the correct framebuffer
  10951. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10952. }
  10953. onBeforeUnbind();
  10954. }
  10955. this.bindUnboundFramebuffer(null);
  10956. };
  10957. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10958. if (texture.generateMipMaps) {
  10959. var gl = this._gl;
  10960. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10961. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10962. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10963. }
  10964. };
  10965. Engine.prototype.flushFramebuffer = function () {
  10966. this._gl.flush();
  10967. };
  10968. Engine.prototype.restoreDefaultFramebuffer = function () {
  10969. if (this._currentRenderTarget) {
  10970. this.unBindFramebuffer(this._currentRenderTarget);
  10971. }
  10972. else {
  10973. this.bindUnboundFramebuffer(null);
  10974. }
  10975. if (this._cachedViewport) {
  10976. this.setViewport(this._cachedViewport);
  10977. }
  10978. this.wipeCaches();
  10979. };
  10980. // UBOs
  10981. Engine.prototype.createUniformBuffer = function (elements) {
  10982. var ubo = this._gl.createBuffer();
  10983. if (!ubo) {
  10984. throw new Error("Unable to create uniform buffer");
  10985. }
  10986. this.bindUniformBuffer(ubo);
  10987. if (elements instanceof Float32Array) {
  10988. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10989. }
  10990. else {
  10991. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10992. }
  10993. this.bindUniformBuffer(null);
  10994. ubo.references = 1;
  10995. return ubo;
  10996. };
  10997. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10998. var ubo = this._gl.createBuffer();
  10999. if (!ubo) {
  11000. throw new Error("Unable to create dynamic uniform buffer");
  11001. }
  11002. this.bindUniformBuffer(ubo);
  11003. if (elements instanceof Float32Array) {
  11004. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11005. }
  11006. else {
  11007. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11008. }
  11009. this.bindUniformBuffer(null);
  11010. ubo.references = 1;
  11011. return ubo;
  11012. };
  11013. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11014. this.bindUniformBuffer(uniformBuffer);
  11015. if (offset === undefined) {
  11016. offset = 0;
  11017. }
  11018. if (count === undefined) {
  11019. if (elements instanceof Float32Array) {
  11020. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11021. }
  11022. else {
  11023. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11024. }
  11025. }
  11026. else {
  11027. if (elements instanceof Float32Array) {
  11028. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11029. }
  11030. else {
  11031. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11032. }
  11033. }
  11034. this.bindUniformBuffer(null);
  11035. };
  11036. // VBOs
  11037. Engine.prototype._resetVertexBufferBinding = function () {
  11038. this.bindArrayBuffer(null);
  11039. this._cachedVertexBuffers = null;
  11040. };
  11041. Engine.prototype.createVertexBuffer = function (vertices) {
  11042. var vbo = this._gl.createBuffer();
  11043. if (!vbo) {
  11044. throw new Error("Unable to create vertex buffer");
  11045. }
  11046. this.bindArrayBuffer(vbo);
  11047. if (vertices instanceof Float32Array) {
  11048. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11049. }
  11050. else {
  11051. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11052. }
  11053. this._resetVertexBufferBinding();
  11054. vbo.references = 1;
  11055. return vbo;
  11056. };
  11057. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11058. var vbo = this._gl.createBuffer();
  11059. if (!vbo) {
  11060. throw new Error("Unable to create dynamic vertex buffer");
  11061. }
  11062. this.bindArrayBuffer(vbo);
  11063. if (vertices instanceof Float32Array) {
  11064. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11065. }
  11066. else {
  11067. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11068. }
  11069. this._resetVertexBufferBinding();
  11070. vbo.references = 1;
  11071. return vbo;
  11072. };
  11073. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11074. if (offset === void 0) { offset = 0; }
  11075. // Force cache update
  11076. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11077. this.bindIndexBuffer(indexBuffer);
  11078. var arrayBuffer;
  11079. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11080. arrayBuffer = indices;
  11081. }
  11082. else {
  11083. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11084. }
  11085. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11086. this._resetIndexBufferBinding();
  11087. };
  11088. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11089. this.bindArrayBuffer(vertexBuffer);
  11090. if (offset === undefined) {
  11091. offset = 0;
  11092. }
  11093. if (count === undefined) {
  11094. if (vertices instanceof Float32Array) {
  11095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11096. }
  11097. else {
  11098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11099. }
  11100. }
  11101. else {
  11102. if (vertices instanceof Float32Array) {
  11103. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11104. }
  11105. else {
  11106. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11107. }
  11108. }
  11109. this._resetVertexBufferBinding();
  11110. };
  11111. Engine.prototype._resetIndexBufferBinding = function () {
  11112. this.bindIndexBuffer(null);
  11113. this._cachedIndexBuffer = null;
  11114. };
  11115. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11116. var vbo = this._gl.createBuffer();
  11117. if (!vbo) {
  11118. throw new Error("Unable to create index buffer");
  11119. }
  11120. this.bindIndexBuffer(vbo);
  11121. // Check for 32 bits indices
  11122. var arrayBuffer;
  11123. var need32Bits = false;
  11124. if (indices instanceof Uint16Array) {
  11125. arrayBuffer = indices;
  11126. }
  11127. else {
  11128. //check 32 bit support
  11129. if (this._caps.uintIndices) {
  11130. if (indices instanceof Uint32Array) {
  11131. arrayBuffer = indices;
  11132. need32Bits = true;
  11133. }
  11134. else {
  11135. //number[] or Int32Array, check if 32 bit is necessary
  11136. for (var index = 0; index < indices.length; index++) {
  11137. if (indices[index] > 65535) {
  11138. need32Bits = true;
  11139. break;
  11140. }
  11141. }
  11142. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11143. }
  11144. }
  11145. else {
  11146. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11147. arrayBuffer = new Uint16Array(indices);
  11148. }
  11149. }
  11150. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11151. this._resetIndexBufferBinding();
  11152. vbo.references = 1;
  11153. vbo.is32Bits = need32Bits;
  11154. return vbo;
  11155. };
  11156. Engine.prototype.bindArrayBuffer = function (buffer) {
  11157. if (!this._vaoRecordInProgress) {
  11158. this._unbindVertexArrayObject();
  11159. }
  11160. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11161. };
  11162. Engine.prototype.bindUniformBuffer = function (buffer) {
  11163. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11164. };
  11165. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11166. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11167. };
  11168. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11169. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11170. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11171. };
  11172. ;
  11173. Engine.prototype.bindIndexBuffer = function (buffer) {
  11174. if (!this._vaoRecordInProgress) {
  11175. this._unbindVertexArrayObject();
  11176. }
  11177. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11178. };
  11179. Engine.prototype.bindBuffer = function (buffer, target) {
  11180. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11181. this._gl.bindBuffer(target, buffer);
  11182. this._currentBoundBuffer[target] = buffer;
  11183. }
  11184. };
  11185. Engine.prototype.updateArrayBuffer = function (data) {
  11186. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11187. };
  11188. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11189. var pointer = this._currentBufferPointers[indx];
  11190. var changed = false;
  11191. if (!pointer.active) {
  11192. changed = true;
  11193. pointer.active = true;
  11194. pointer.index = indx;
  11195. pointer.size = size;
  11196. pointer.type = type;
  11197. pointer.normalized = normalized;
  11198. pointer.stride = stride;
  11199. pointer.offset = offset;
  11200. pointer.buffer = buffer;
  11201. }
  11202. else {
  11203. if (pointer.buffer !== buffer) {
  11204. pointer.buffer = buffer;
  11205. changed = true;
  11206. }
  11207. if (pointer.size !== size) {
  11208. pointer.size = size;
  11209. changed = true;
  11210. }
  11211. if (pointer.type !== type) {
  11212. pointer.type = type;
  11213. changed = true;
  11214. }
  11215. if (pointer.normalized !== normalized) {
  11216. pointer.normalized = normalized;
  11217. changed = true;
  11218. }
  11219. if (pointer.stride !== stride) {
  11220. pointer.stride = stride;
  11221. changed = true;
  11222. }
  11223. if (pointer.offset !== offset) {
  11224. pointer.offset = offset;
  11225. changed = true;
  11226. }
  11227. }
  11228. if (changed || this._vaoRecordInProgress) {
  11229. this.bindArrayBuffer(buffer);
  11230. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11231. }
  11232. };
  11233. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11234. if (indexBuffer == null) {
  11235. return;
  11236. }
  11237. if (this._cachedIndexBuffer !== indexBuffer) {
  11238. this._cachedIndexBuffer = indexBuffer;
  11239. this.bindIndexBuffer(indexBuffer);
  11240. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11241. }
  11242. };
  11243. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11244. var attributes = effect.getAttributesNames();
  11245. if (!this._vaoRecordInProgress) {
  11246. this._unbindVertexArrayObject();
  11247. }
  11248. this.unbindAllAttributes();
  11249. for (var index = 0; index < attributes.length; index++) {
  11250. var order = effect.getAttributeLocation(index);
  11251. if (order >= 0) {
  11252. var vertexBuffer = vertexBuffers[attributes[index]];
  11253. if (!vertexBuffer) {
  11254. continue;
  11255. }
  11256. this._gl.enableVertexAttribArray(order);
  11257. if (!this._vaoRecordInProgress) {
  11258. this._vertexAttribArraysEnabled[order] = true;
  11259. }
  11260. var buffer = vertexBuffer.getBuffer();
  11261. if (buffer) {
  11262. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11263. if (vertexBuffer.getIsInstanced()) {
  11264. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11265. if (!this._vaoRecordInProgress) {
  11266. this._currentInstanceLocations.push(order);
  11267. this._currentInstanceBuffers.push(buffer);
  11268. }
  11269. }
  11270. }
  11271. }
  11272. }
  11273. };
  11274. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11275. var vao = this._gl.createVertexArray();
  11276. this._vaoRecordInProgress = true;
  11277. this._gl.bindVertexArray(vao);
  11278. this._mustWipeVertexAttributes = true;
  11279. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11280. this.bindIndexBuffer(indexBuffer);
  11281. this._vaoRecordInProgress = false;
  11282. this._gl.bindVertexArray(null);
  11283. return vao;
  11284. };
  11285. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11286. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11287. this._cachedVertexArrayObject = vertexArrayObject;
  11288. this._gl.bindVertexArray(vertexArrayObject);
  11289. this._cachedVertexBuffers = null;
  11290. this._cachedIndexBuffer = null;
  11291. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11292. this._mustWipeVertexAttributes = true;
  11293. }
  11294. };
  11295. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11296. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11297. this._cachedVertexBuffers = vertexBuffer;
  11298. this._cachedEffectForVertexBuffers = effect;
  11299. var attributesCount = effect.getAttributesCount();
  11300. this._unbindVertexArrayObject();
  11301. this.unbindAllAttributes();
  11302. var offset = 0;
  11303. for (var index = 0; index < attributesCount; index++) {
  11304. if (index < vertexDeclaration.length) {
  11305. var order = effect.getAttributeLocation(index);
  11306. if (order >= 0) {
  11307. this._gl.enableVertexAttribArray(order);
  11308. this._vertexAttribArraysEnabled[order] = true;
  11309. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11310. }
  11311. offset += vertexDeclaration[index] * 4;
  11312. }
  11313. }
  11314. }
  11315. this._bindIndexBufferWithCache(indexBuffer);
  11316. };
  11317. Engine.prototype._unbindVertexArrayObject = function () {
  11318. if (!this._cachedVertexArrayObject) {
  11319. return;
  11320. }
  11321. this._cachedVertexArrayObject = null;
  11322. this._gl.bindVertexArray(null);
  11323. };
  11324. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11325. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11326. this._cachedVertexBuffers = vertexBuffers;
  11327. this._cachedEffectForVertexBuffers = effect;
  11328. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11329. }
  11330. this._bindIndexBufferWithCache(indexBuffer);
  11331. };
  11332. Engine.prototype.unbindInstanceAttributes = function () {
  11333. var boundBuffer;
  11334. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11335. var instancesBuffer = this._currentInstanceBuffers[i];
  11336. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11337. boundBuffer = instancesBuffer;
  11338. this.bindArrayBuffer(instancesBuffer);
  11339. }
  11340. var offsetLocation = this._currentInstanceLocations[i];
  11341. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11342. }
  11343. this._currentInstanceBuffers.length = 0;
  11344. this._currentInstanceLocations.length = 0;
  11345. };
  11346. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11347. this._gl.deleteVertexArray(vao);
  11348. };
  11349. Engine.prototype._releaseBuffer = function (buffer) {
  11350. buffer.references--;
  11351. if (buffer.references === 0) {
  11352. this._gl.deleteBuffer(buffer);
  11353. return true;
  11354. }
  11355. return false;
  11356. };
  11357. Engine.prototype.createInstancesBuffer = function (capacity) {
  11358. var buffer = this._gl.createBuffer();
  11359. if (!buffer) {
  11360. throw new Error("Unable to create instance buffer");
  11361. }
  11362. buffer.capacity = capacity;
  11363. this.bindArrayBuffer(buffer);
  11364. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11365. return buffer;
  11366. };
  11367. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11368. this._gl.deleteBuffer(buffer);
  11369. };
  11370. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11371. this.bindArrayBuffer(instancesBuffer);
  11372. if (data) {
  11373. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11374. }
  11375. if (offsetLocations[0].index !== undefined) {
  11376. var stride = 0;
  11377. for (var i = 0; i < offsetLocations.length; i++) {
  11378. var ai = offsetLocations[i];
  11379. stride += ai.attributeSize * 4;
  11380. }
  11381. for (var i = 0; i < offsetLocations.length; i++) {
  11382. var ai = offsetLocations[i];
  11383. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11384. this._gl.enableVertexAttribArray(ai.index);
  11385. this._vertexAttribArraysEnabled[ai.index] = true;
  11386. }
  11387. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11388. this._gl.vertexAttribDivisor(ai.index, 1);
  11389. this._currentInstanceLocations.push(ai.index);
  11390. this._currentInstanceBuffers.push(instancesBuffer);
  11391. }
  11392. }
  11393. else {
  11394. for (var index = 0; index < 4; index++) {
  11395. var offsetLocation = offsetLocations[index];
  11396. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11397. this._gl.enableVertexAttribArray(offsetLocation);
  11398. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11399. }
  11400. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11401. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11402. this._currentInstanceLocations.push(offsetLocation);
  11403. this._currentInstanceBuffers.push(instancesBuffer);
  11404. }
  11405. }
  11406. };
  11407. Engine.prototype.applyStates = function () {
  11408. this._depthCullingState.apply(this._gl);
  11409. this._stencilState.apply(this._gl);
  11410. this._alphaState.apply(this._gl);
  11411. };
  11412. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11413. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11414. };
  11415. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11416. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11417. };
  11418. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11419. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11420. };
  11421. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11422. // Apply states
  11423. this.applyStates();
  11424. this._drawCalls.addCount(1, false);
  11425. // Render
  11426. var drawMode = this.DrawMode(fillMode);
  11427. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11428. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11429. if (instancesCount) {
  11430. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11431. }
  11432. else {
  11433. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11434. }
  11435. };
  11436. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11437. // Apply states
  11438. this.applyStates();
  11439. this._drawCalls.addCount(1, false);
  11440. var drawMode = this.DrawMode(fillMode);
  11441. if (instancesCount) {
  11442. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11443. }
  11444. else {
  11445. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11446. }
  11447. };
  11448. Engine.prototype.DrawMode = function (fillMode) {
  11449. switch (fillMode) {
  11450. // Triangle views
  11451. case BABYLON.Material.TriangleFillMode:
  11452. return this._gl.TRIANGLES;
  11453. case BABYLON.Material.PointFillMode:
  11454. return this._gl.POINTS;
  11455. case BABYLON.Material.WireFrameFillMode:
  11456. return this._gl.LINES;
  11457. // Draw modes
  11458. case BABYLON.Material.PointListDrawMode:
  11459. return this._gl.POINTS;
  11460. case BABYLON.Material.LineListDrawMode:
  11461. return this._gl.LINES;
  11462. case BABYLON.Material.LineLoopDrawMode:
  11463. return this._gl.LINE_LOOP;
  11464. case BABYLON.Material.LineStripDrawMode:
  11465. return this._gl.LINE_STRIP;
  11466. case BABYLON.Material.TriangleStripDrawMode:
  11467. return this._gl.TRIANGLE_STRIP;
  11468. case BABYLON.Material.TriangleFanDrawMode:
  11469. return this._gl.TRIANGLE_FAN;
  11470. default:
  11471. return this._gl.TRIANGLES;
  11472. }
  11473. };
  11474. // Shaders
  11475. Engine.prototype._releaseEffect = function (effect) {
  11476. if (this._compiledEffects[effect._key]) {
  11477. delete this._compiledEffects[effect._key];
  11478. this._deleteProgram(effect.getProgram());
  11479. }
  11480. };
  11481. Engine.prototype._deleteProgram = function (program) {
  11482. if (program) {
  11483. program.__SPECTOR_rebuildProgram = null;
  11484. if (program.transformFeedback) {
  11485. this.deleteTransformFeedback(program.transformFeedback);
  11486. program.transformFeedback = null;
  11487. }
  11488. this._gl.deleteProgram(program);
  11489. }
  11490. };
  11491. /**
  11492. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11493. * @param samplers An array of string used to represent textures
  11494. */
  11495. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11496. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11497. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11498. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11499. if (this._compiledEffects[name]) {
  11500. var compiledEffect = this._compiledEffects[name];
  11501. if (onCompiled && compiledEffect.isReady()) {
  11502. onCompiled(compiledEffect);
  11503. }
  11504. return compiledEffect;
  11505. }
  11506. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11507. effect._key = name;
  11508. this._compiledEffects[name] = effect;
  11509. return effect;
  11510. };
  11511. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11512. if (uniformsNames === void 0) { uniformsNames = []; }
  11513. if (samplers === void 0) { samplers = []; }
  11514. if (defines === void 0) { defines = ""; }
  11515. return this.createEffect({
  11516. vertex: "particles",
  11517. fragmentElement: fragmentName
  11518. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11519. };
  11520. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11521. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11522. context = context || this._gl;
  11523. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11524. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11525. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11526. };
  11527. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11528. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11529. context = context || this._gl;
  11530. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11531. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11532. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11533. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11534. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11535. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11536. return program;
  11537. };
  11538. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11539. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11540. var shaderProgram = context.createProgram();
  11541. if (!shaderProgram) {
  11542. throw new Error("Unable to create program");
  11543. }
  11544. context.attachShader(shaderProgram, vertexShader);
  11545. context.attachShader(shaderProgram, fragmentShader);
  11546. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11547. var transformFeedback = this.createTransformFeedback();
  11548. this.bindTransformFeedback(transformFeedback);
  11549. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11550. shaderProgram.transformFeedback = transformFeedback;
  11551. }
  11552. context.linkProgram(shaderProgram);
  11553. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11554. this.bindTransformFeedback(null);
  11555. }
  11556. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11557. if (!linked) {
  11558. context.validateProgram(shaderProgram);
  11559. var error = context.getProgramInfoLog(shaderProgram);
  11560. if (error) {
  11561. throw new Error(error);
  11562. }
  11563. }
  11564. context.deleteShader(vertexShader);
  11565. context.deleteShader(fragmentShader);
  11566. return shaderProgram;
  11567. };
  11568. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11569. var results = new Array();
  11570. for (var index = 0; index < uniformsNames.length; index++) {
  11571. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11572. }
  11573. return results;
  11574. };
  11575. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11576. var results = [];
  11577. for (var index = 0; index < attributesNames.length; index++) {
  11578. try {
  11579. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11580. }
  11581. catch (e) {
  11582. results.push(-1);
  11583. }
  11584. }
  11585. return results;
  11586. };
  11587. Engine.prototype.enableEffect = function (effect) {
  11588. if (!effect) {
  11589. return;
  11590. }
  11591. // Use program
  11592. this.bindSamplers(effect);
  11593. this._currentEffect = effect;
  11594. if (effect.onBind) {
  11595. effect.onBind(effect);
  11596. }
  11597. effect.onBindObservable.notifyObservers(effect);
  11598. };
  11599. Engine.prototype.setIntArray = function (uniform, array) {
  11600. if (!uniform)
  11601. return;
  11602. this._gl.uniform1iv(uniform, array);
  11603. };
  11604. Engine.prototype.setIntArray2 = function (uniform, array) {
  11605. if (!uniform || array.length % 2 !== 0)
  11606. return;
  11607. this._gl.uniform2iv(uniform, array);
  11608. };
  11609. Engine.prototype.setIntArray3 = function (uniform, array) {
  11610. if (!uniform || array.length % 3 !== 0)
  11611. return;
  11612. this._gl.uniform3iv(uniform, array);
  11613. };
  11614. Engine.prototype.setIntArray4 = function (uniform, array) {
  11615. if (!uniform || array.length % 4 !== 0)
  11616. return;
  11617. this._gl.uniform4iv(uniform, array);
  11618. };
  11619. Engine.prototype.setFloatArray = function (uniform, array) {
  11620. if (!uniform)
  11621. return;
  11622. this._gl.uniform1fv(uniform, array);
  11623. };
  11624. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11625. if (!uniform || array.length % 2 !== 0)
  11626. return;
  11627. this._gl.uniform2fv(uniform, array);
  11628. };
  11629. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11630. if (!uniform || array.length % 3 !== 0)
  11631. return;
  11632. this._gl.uniform3fv(uniform, array);
  11633. };
  11634. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11635. if (!uniform || array.length % 4 !== 0)
  11636. return;
  11637. this._gl.uniform4fv(uniform, array);
  11638. };
  11639. Engine.prototype.setArray = function (uniform, array) {
  11640. if (!uniform)
  11641. return;
  11642. this._gl.uniform1fv(uniform, array);
  11643. };
  11644. Engine.prototype.setArray2 = function (uniform, array) {
  11645. if (!uniform || array.length % 2 !== 0)
  11646. return;
  11647. this._gl.uniform2fv(uniform, array);
  11648. };
  11649. Engine.prototype.setArray3 = function (uniform, array) {
  11650. if (!uniform || array.length % 3 !== 0)
  11651. return;
  11652. this._gl.uniform3fv(uniform, array);
  11653. };
  11654. Engine.prototype.setArray4 = function (uniform, array) {
  11655. if (!uniform || array.length % 4 !== 0)
  11656. return;
  11657. this._gl.uniform4fv(uniform, array);
  11658. };
  11659. Engine.prototype.setMatrices = function (uniform, matrices) {
  11660. if (!uniform)
  11661. return;
  11662. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11663. };
  11664. Engine.prototype.setMatrix = function (uniform, matrix) {
  11665. if (!uniform)
  11666. return;
  11667. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11668. };
  11669. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11670. if (!uniform)
  11671. return;
  11672. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11673. };
  11674. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11675. if (!uniform)
  11676. return;
  11677. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11678. };
  11679. Engine.prototype.setInt = function (uniform, value) {
  11680. if (!uniform)
  11681. return;
  11682. this._gl.uniform1i(uniform, value);
  11683. };
  11684. Engine.prototype.setFloat = function (uniform, value) {
  11685. if (!uniform)
  11686. return;
  11687. this._gl.uniform1f(uniform, value);
  11688. };
  11689. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11690. if (!uniform)
  11691. return;
  11692. this._gl.uniform2f(uniform, x, y);
  11693. };
  11694. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11695. if (!uniform)
  11696. return;
  11697. this._gl.uniform3f(uniform, x, y, z);
  11698. };
  11699. Engine.prototype.setBool = function (uniform, bool) {
  11700. if (!uniform)
  11701. return;
  11702. this._gl.uniform1i(uniform, bool);
  11703. };
  11704. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11705. if (!uniform)
  11706. return;
  11707. this._gl.uniform4f(uniform, x, y, z, w);
  11708. };
  11709. Engine.prototype.setColor3 = function (uniform, color3) {
  11710. if (!uniform)
  11711. return;
  11712. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11713. };
  11714. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11715. if (!uniform)
  11716. return;
  11717. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11718. };
  11719. // States
  11720. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11721. if (zOffset === void 0) { zOffset = 0; }
  11722. if (reverseSide === void 0) { reverseSide = false; }
  11723. // Culling
  11724. if (this._depthCullingState.cull !== culling || force) {
  11725. this._depthCullingState.cull = culling;
  11726. }
  11727. // Cull face
  11728. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11729. if (this._depthCullingState.cullFace !== cullFace || force) {
  11730. this._depthCullingState.cullFace = cullFace;
  11731. }
  11732. // Z offset
  11733. this.setZOffset(zOffset);
  11734. // Front face
  11735. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11736. if (this._depthCullingState.frontFace !== frontFace || force) {
  11737. this._depthCullingState.frontFace = frontFace;
  11738. }
  11739. };
  11740. Engine.prototype.setZOffset = function (value) {
  11741. this._depthCullingState.zOffset = value;
  11742. };
  11743. Engine.prototype.getZOffset = function () {
  11744. return this._depthCullingState.zOffset;
  11745. };
  11746. Engine.prototype.setDepthBuffer = function (enable) {
  11747. this._depthCullingState.depthTest = enable;
  11748. };
  11749. Engine.prototype.getDepthWrite = function () {
  11750. return this._depthCullingState.depthMask;
  11751. };
  11752. Engine.prototype.setDepthWrite = function (enable) {
  11753. this._depthCullingState.depthMask = enable;
  11754. };
  11755. Engine.prototype.setColorWrite = function (enable) {
  11756. this._gl.colorMask(enable, enable, enable, enable);
  11757. this._colorWrite = enable;
  11758. };
  11759. Engine.prototype.getColorWrite = function () {
  11760. return this._colorWrite;
  11761. };
  11762. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11763. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11764. };
  11765. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11766. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11767. if (this._alphaMode === mode) {
  11768. return;
  11769. }
  11770. switch (mode) {
  11771. case Engine.ALPHA_DISABLE:
  11772. this._alphaState.alphaBlend = false;
  11773. break;
  11774. case Engine.ALPHA_PREMULTIPLIED:
  11775. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11776. this._alphaState.alphaBlend = true;
  11777. break;
  11778. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11779. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11780. this._alphaState.alphaBlend = true;
  11781. break;
  11782. case Engine.ALPHA_COMBINE:
  11783. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11784. this._alphaState.alphaBlend = true;
  11785. break;
  11786. case Engine.ALPHA_ONEONE:
  11787. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11788. this._alphaState.alphaBlend = true;
  11789. break;
  11790. case Engine.ALPHA_ADD:
  11791. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11792. this._alphaState.alphaBlend = true;
  11793. break;
  11794. case Engine.ALPHA_SUBTRACT:
  11795. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11796. this._alphaState.alphaBlend = true;
  11797. break;
  11798. case Engine.ALPHA_MULTIPLY:
  11799. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11800. this._alphaState.alphaBlend = true;
  11801. break;
  11802. case Engine.ALPHA_MAXIMIZED:
  11803. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11804. this._alphaState.alphaBlend = true;
  11805. break;
  11806. case Engine.ALPHA_INTERPOLATE:
  11807. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11808. this._alphaState.alphaBlend = true;
  11809. break;
  11810. case Engine.ALPHA_SCREENMODE:
  11811. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11812. this._alphaState.alphaBlend = true;
  11813. break;
  11814. }
  11815. if (!noDepthWriteChange) {
  11816. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11817. }
  11818. this._alphaMode = mode;
  11819. };
  11820. Engine.prototype.getAlphaMode = function () {
  11821. return this._alphaMode;
  11822. };
  11823. // Textures
  11824. Engine.prototype.wipeCaches = function (bruteForce) {
  11825. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11826. return;
  11827. }
  11828. this._currentEffect = null;
  11829. // 6/8/2017: deltakosh: Should not be required anymore.
  11830. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11831. if (bruteForce) {
  11832. this.resetTextureCache();
  11833. this._currentProgram = null;
  11834. this._stencilState.reset();
  11835. this._depthCullingState.reset();
  11836. this.setDepthFunctionToLessOrEqual();
  11837. this._alphaState.reset();
  11838. }
  11839. this._resetVertexBufferBinding();
  11840. this._cachedIndexBuffer = null;
  11841. this._cachedEffectForVertexBuffers = null;
  11842. this._unbindVertexArrayObject();
  11843. this.bindIndexBuffer(null);
  11844. };
  11845. /**
  11846. * Set the compressed texture format to use, based on the formats you have, and the formats
  11847. * supported by the hardware / browser.
  11848. *
  11849. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11850. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11851. * to API arguments needed to compressed textures. This puts the burden on the container
  11852. * generator to house the arcane code for determining these for current & future formats.
  11853. *
  11854. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11855. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11856. *
  11857. * Note: The result of this call is not taken into account when a texture is base64.
  11858. *
  11859. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11860. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11861. *
  11862. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11863. * @returns The extension selected.
  11864. */
  11865. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11866. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11867. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11868. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11869. return this._textureFormatInUse = this._texturesSupported[i];
  11870. }
  11871. }
  11872. }
  11873. // actively set format to nothing, to allow this to be called more than once
  11874. // and possibly fail the 2nd time
  11875. this._textureFormatInUse = null;
  11876. return null;
  11877. };
  11878. Engine.prototype._createTexture = function () {
  11879. var texture = this._gl.createTexture();
  11880. if (!texture) {
  11881. throw new Error("Unable to create texture");
  11882. }
  11883. return texture;
  11884. };
  11885. /**
  11886. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11887. * @param {string} urlArg- This contains one of the following:
  11888. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11889. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11890. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11891. *
  11892. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11893. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11894. * @param {Scene} scene- Needed for loading to the correct scene.
  11895. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11896. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11897. * @param {callback} onError- Optional callback to be called upon failure.
  11898. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11899. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11900. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11901. *
  11902. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11903. */
  11904. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11905. var _this = this;
  11906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11907. if (onLoad === void 0) { onLoad = null; }
  11908. if (onError === void 0) { onError = null; }
  11909. if (buffer === void 0) { buffer = null; }
  11910. if (fallBack === void 0) { fallBack = null; }
  11911. if (format === void 0) { format = null; }
  11912. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11913. var fromData = url.substr(0, 5) === "data:";
  11914. var fromBlob = url.substr(0, 5) === "blob:";
  11915. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11916. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11917. // establish the file extension, if possible
  11918. var lastDot = url.lastIndexOf('.');
  11919. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11920. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  11921. var isTGA = (extension.indexOf(".tga") === 0);
  11922. // determine if a ktx file should be substituted
  11923. var isKTX = false;
  11924. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11925. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11926. isKTX = true;
  11927. }
  11928. if (scene) {
  11929. scene._addPendingData(texture);
  11930. }
  11931. texture.url = url;
  11932. texture.generateMipMaps = !noMipmap;
  11933. texture.samplingMode = samplingMode;
  11934. texture.invertY = invertY;
  11935. if (!this._doNotHandleContextLost) {
  11936. // Keep a link to the buffer only if we plan to handle context lost
  11937. texture._buffer = buffer;
  11938. }
  11939. var onLoadObserver = null;
  11940. if (onLoad && !fallBack) {
  11941. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11942. }
  11943. if (!fallBack)
  11944. this._internalTexturesCache.push(texture);
  11945. var onerror = function (message, exception) {
  11946. if (scene) {
  11947. scene._removePendingData(texture);
  11948. }
  11949. if (onLoadObserver) {
  11950. texture.onLoadedObservable.remove(onLoadObserver);
  11951. }
  11952. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11953. if (isKTX) {
  11954. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11955. }
  11956. else if (BABYLON.Tools.UseFallbackTexture) {
  11957. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11958. }
  11959. if (onError) {
  11960. onError(message || "Unknown error", exception);
  11961. }
  11962. };
  11963. var callback = null;
  11964. // processing for non-image formats
  11965. if (isKTX || isTGA || isDDS) {
  11966. if (isKTX) {
  11967. callback = function (data) {
  11968. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11969. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11970. ktx.uploadLevels(_this._gl, !noMipmap);
  11971. return false;
  11972. }, samplingMode);
  11973. };
  11974. }
  11975. else if (isTGA) {
  11976. callback = function (arrayBuffer) {
  11977. var data = new Uint8Array(arrayBuffer);
  11978. var header = BABYLON.TGATools.GetTGAHeader(data);
  11979. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11980. BABYLON.TGATools.UploadContent(_this._gl, data);
  11981. return false;
  11982. }, samplingMode);
  11983. };
  11984. }
  11985. else if (isDDS) {
  11986. callback = function (data) {
  11987. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11988. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11989. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11990. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11991. return false;
  11992. }, samplingMode);
  11993. };
  11994. }
  11995. if (!buffer) {
  11996. this._loadFile(url, function (data) {
  11997. if (callback) {
  11998. callback(data);
  11999. }
  12000. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12001. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12002. });
  12003. }
  12004. else {
  12005. if (callback) {
  12006. callback(buffer);
  12007. }
  12008. }
  12009. // image format processing
  12010. }
  12011. else {
  12012. var onload = function (img) {
  12013. if (fromBlob && !_this._doNotHandleContextLost) {
  12014. // We need to store the image if we need to rebuild the texture
  12015. // in case of a webgl context lost
  12016. texture._buffer = img;
  12017. }
  12018. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12019. var gl = _this._gl;
  12020. var isPot = (img.width === potWidth && img.height === potHeight);
  12021. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12022. if (isPot) {
  12023. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12024. return false;
  12025. }
  12026. // Using shaders to rescale because canvas.drawImage is lossy
  12027. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12028. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12029. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12032. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12033. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12034. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12035. _this._releaseTexture(source);
  12036. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12037. continuationCallback();
  12038. });
  12039. return true;
  12040. }, samplingMode);
  12041. };
  12042. if (!fromData || isBase64)
  12043. if (buffer instanceof HTMLImageElement) {
  12044. onload(buffer);
  12045. }
  12046. else {
  12047. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12048. }
  12049. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12050. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12051. else
  12052. onload(buffer);
  12053. }
  12054. return texture;
  12055. };
  12056. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12057. var _this = this;
  12058. var rtt = this.createRenderTargetTexture({
  12059. width: destination.width,
  12060. height: destination.height,
  12061. }, {
  12062. generateMipMaps: false,
  12063. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12064. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12065. generateDepthBuffer: false,
  12066. generateStencilBuffer: false
  12067. });
  12068. if (!this._rescalePostProcess) {
  12069. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12070. }
  12071. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12072. _this._rescalePostProcess.onApply = function (effect) {
  12073. effect._bindTexture("textureSampler", source);
  12074. };
  12075. var hostingScene = scene;
  12076. if (!hostingScene) {
  12077. hostingScene = _this.scenes[_this.scenes.length - 1];
  12078. }
  12079. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12080. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12081. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12082. _this.unBindFramebuffer(rtt);
  12083. _this._releaseTexture(rtt);
  12084. if (onComplete) {
  12085. onComplete();
  12086. }
  12087. });
  12088. };
  12089. Engine.prototype._getInternalFormat = function (format) {
  12090. var internalFormat = this._gl.RGBA;
  12091. switch (format) {
  12092. case Engine.TEXTUREFORMAT_ALPHA:
  12093. internalFormat = this._gl.ALPHA;
  12094. break;
  12095. case Engine.TEXTUREFORMAT_LUMINANCE:
  12096. internalFormat = this._gl.LUMINANCE;
  12097. break;
  12098. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12099. internalFormat = this._gl.LUMINANCE_ALPHA;
  12100. break;
  12101. case Engine.TEXTUREFORMAT_RGB:
  12102. internalFormat = this._gl.RGB;
  12103. break;
  12104. case Engine.TEXTUREFORMAT_RGBA:
  12105. internalFormat = this._gl.RGBA;
  12106. break;
  12107. }
  12108. return internalFormat;
  12109. };
  12110. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12111. if (compression === void 0) { compression = null; }
  12112. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12113. if (!texture) {
  12114. return;
  12115. }
  12116. var internalFormat = this._getInternalFormat(format);
  12117. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12118. var textureType = this._getWebGLTextureType(type);
  12119. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12120. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12121. if (!this._doNotHandleContextLost) {
  12122. texture._bufferView = data;
  12123. texture.format = format;
  12124. texture.type = type;
  12125. texture.invertY = invertY;
  12126. texture._compression = compression;
  12127. }
  12128. if (texture.width % 4 !== 0) {
  12129. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12130. }
  12131. if (compression && data) {
  12132. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12133. }
  12134. else {
  12135. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12136. }
  12137. if (texture.generateMipMaps) {
  12138. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12139. }
  12140. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12141. // this.resetTextureCache();
  12142. texture.isReady = true;
  12143. };
  12144. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12145. if (compression === void 0) { compression = null; }
  12146. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12147. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12148. texture.baseWidth = width;
  12149. texture.baseHeight = height;
  12150. texture.width = width;
  12151. texture.height = height;
  12152. texture.format = format;
  12153. texture.generateMipMaps = generateMipMaps;
  12154. texture.samplingMode = samplingMode;
  12155. texture.invertY = invertY;
  12156. texture._compression = compression;
  12157. texture.type = type;
  12158. if (!this._doNotHandleContextLost) {
  12159. texture._bufferView = data;
  12160. }
  12161. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12162. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12163. // Filters
  12164. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12165. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12166. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12167. if (generateMipMaps) {
  12168. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12169. }
  12170. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12171. this._internalTexturesCache.push(texture);
  12172. return texture;
  12173. };
  12174. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12175. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12176. texture.baseWidth = width;
  12177. texture.baseHeight = height;
  12178. if (generateMipMaps) {
  12179. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12180. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12181. }
  12182. // this.resetTextureCache();
  12183. texture.width = width;
  12184. texture.height = height;
  12185. texture.isReady = false;
  12186. texture.generateMipMaps = generateMipMaps;
  12187. texture.samplingMode = samplingMode;
  12188. this.updateTextureSamplingMode(samplingMode, texture);
  12189. this._internalTexturesCache.push(texture);
  12190. return texture;
  12191. };
  12192. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12193. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12194. if (texture.isCube) {
  12195. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12196. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12197. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12198. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12199. }
  12200. else if (texture.is3D) {
  12201. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12204. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12205. }
  12206. else {
  12207. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12208. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12210. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12211. }
  12212. texture.samplingMode = samplingMode;
  12213. };
  12214. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12215. if (premulAlpha === void 0) { premulAlpha = false; }
  12216. if (!texture) {
  12217. return;
  12218. }
  12219. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12220. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12221. if (premulAlpha) {
  12222. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12223. }
  12224. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12225. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12226. if (texture.generateMipMaps) {
  12227. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12228. }
  12229. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12230. if (premulAlpha) {
  12231. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12232. }
  12233. texture.isReady = true;
  12234. };
  12235. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12236. if (!texture || texture._isDisabled) {
  12237. return;
  12238. }
  12239. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12240. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12241. try {
  12242. // Testing video texture support
  12243. if (this._videoTextureSupported === undefined) {
  12244. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12245. if (this._gl.getError() !== 0) {
  12246. this._videoTextureSupported = false;
  12247. }
  12248. else {
  12249. this._videoTextureSupported = true;
  12250. }
  12251. }
  12252. // Copy video through the current working canvas if video texture is not supported
  12253. if (!this._videoTextureSupported) {
  12254. if (!texture._workingCanvas) {
  12255. texture._workingCanvas = document.createElement("canvas");
  12256. var context = texture._workingCanvas.getContext("2d");
  12257. if (!context) {
  12258. throw new Error("Unable to get 2d context");
  12259. }
  12260. texture._workingContext = context;
  12261. texture._workingCanvas.width = texture.width;
  12262. texture._workingCanvas.height = texture.height;
  12263. }
  12264. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12265. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12266. }
  12267. else {
  12268. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12269. }
  12270. if (texture.generateMipMaps) {
  12271. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12272. }
  12273. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12274. // this.resetTextureCache();
  12275. texture.isReady = true;
  12276. }
  12277. catch (ex) {
  12278. // Something unexpected
  12279. // Let's disable the texture
  12280. texture._isDisabled = true;
  12281. }
  12282. };
  12283. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12284. var fullOptions = new RenderTargetCreationOptions();
  12285. if (options !== undefined && typeof options === "object") {
  12286. fullOptions.generateMipMaps = options.generateMipMaps;
  12287. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12288. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12289. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12290. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12291. }
  12292. else {
  12293. fullOptions.generateMipMaps = options;
  12294. fullOptions.generateDepthBuffer = true;
  12295. fullOptions.generateStencilBuffer = false;
  12296. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12297. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12298. }
  12299. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12300. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12301. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12302. }
  12303. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12304. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12305. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12306. }
  12307. var gl = this._gl;
  12308. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12309. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12310. var width = size.width || size;
  12311. var height = size.height || size;
  12312. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12313. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12314. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12315. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12316. }
  12317. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12321. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12322. // Create the framebuffer
  12323. var framebuffer = gl.createFramebuffer();
  12324. this.bindUnboundFramebuffer(framebuffer);
  12325. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12326. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12327. if (fullOptions.generateMipMaps) {
  12328. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12329. }
  12330. // Unbind
  12331. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12332. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12333. this.bindUnboundFramebuffer(null);
  12334. texture._framebuffer = framebuffer;
  12335. texture.baseWidth = width;
  12336. texture.baseHeight = height;
  12337. texture.width = width;
  12338. texture.height = height;
  12339. texture.isReady = true;
  12340. texture.samples = 1;
  12341. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12342. texture.samplingMode = fullOptions.samplingMode;
  12343. texture.type = fullOptions.type;
  12344. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12345. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12346. // this.resetTextureCache();
  12347. this._internalTexturesCache.push(texture);
  12348. return texture;
  12349. };
  12350. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12351. var generateMipMaps = false;
  12352. var generateDepthBuffer = true;
  12353. var generateStencilBuffer = false;
  12354. var generateDepthTexture = false;
  12355. var textureCount = 1;
  12356. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12357. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12358. var types = [], samplingModes = [];
  12359. if (options !== undefined) {
  12360. generateMipMaps = options.generateMipMaps;
  12361. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12362. generateStencilBuffer = options.generateStencilBuffer;
  12363. generateDepthTexture = options.generateDepthTexture;
  12364. textureCount = options.textureCount || 1;
  12365. if (options.types) {
  12366. types = options.types;
  12367. }
  12368. if (options.samplingModes) {
  12369. samplingModes = options.samplingModes;
  12370. }
  12371. }
  12372. var gl = this._gl;
  12373. // Create the framebuffer
  12374. var framebuffer = gl.createFramebuffer();
  12375. this.bindUnboundFramebuffer(framebuffer);
  12376. var width = size.width || size;
  12377. var height = size.height || size;
  12378. var textures = [];
  12379. var attachments = [];
  12380. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12381. for (var i = 0; i < textureCount; i++) {
  12382. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12383. var type = types[i] || defaultType;
  12384. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12385. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12386. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12387. }
  12388. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12389. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12390. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12391. }
  12392. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12393. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12394. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12395. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12396. }
  12397. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12398. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12399. textures.push(texture);
  12400. attachments.push(attachment);
  12401. gl.activeTexture(gl["TEXTURE" + i]);
  12402. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12403. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12407. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12408. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12409. if (generateMipMaps) {
  12410. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12411. }
  12412. // Unbind
  12413. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12414. texture._framebuffer = framebuffer;
  12415. texture._depthStencilBuffer = depthStencilBuffer;
  12416. texture.baseWidth = width;
  12417. texture.baseHeight = height;
  12418. texture.width = width;
  12419. texture.height = height;
  12420. texture.isReady = true;
  12421. texture.samples = 1;
  12422. texture.generateMipMaps = generateMipMaps;
  12423. texture.samplingMode = samplingMode;
  12424. texture.type = type;
  12425. texture._generateDepthBuffer = generateDepthBuffer;
  12426. texture._generateStencilBuffer = generateStencilBuffer;
  12427. texture._attachments = attachments;
  12428. this._internalTexturesCache.push(texture);
  12429. }
  12430. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12431. // Depth texture
  12432. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12433. gl.activeTexture(gl.TEXTURE0);
  12434. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12439. 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);
  12440. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12441. depthTexture._framebuffer = framebuffer;
  12442. depthTexture.baseWidth = width;
  12443. depthTexture.baseHeight = height;
  12444. depthTexture.width = width;
  12445. depthTexture.height = height;
  12446. depthTexture.isReady = true;
  12447. depthTexture.samples = 1;
  12448. depthTexture.generateMipMaps = generateMipMaps;
  12449. depthTexture.samplingMode = gl.NEAREST;
  12450. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12451. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12452. textures.push(depthTexture);
  12453. this._internalTexturesCache.push(depthTexture);
  12454. }
  12455. gl.drawBuffers(attachments);
  12456. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12457. this.bindUnboundFramebuffer(null);
  12458. this.resetTextureCache();
  12459. return textures;
  12460. };
  12461. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12462. if (samples === void 0) { samples = 1; }
  12463. var depthStencilBuffer = null;
  12464. var gl = this._gl;
  12465. // Create the depth/stencil buffer
  12466. if (generateStencilBuffer) {
  12467. depthStencilBuffer = gl.createRenderbuffer();
  12468. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12469. if (samples > 1) {
  12470. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12471. }
  12472. else {
  12473. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12474. }
  12475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12476. }
  12477. else if (generateDepthBuffer) {
  12478. depthStencilBuffer = gl.createRenderbuffer();
  12479. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12480. if (samples > 1) {
  12481. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12482. }
  12483. else {
  12484. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12485. }
  12486. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12487. }
  12488. return depthStencilBuffer;
  12489. };
  12490. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12491. if (this.webGLVersion < 2 || !texture) {
  12492. return 1;
  12493. }
  12494. if (texture.samples === samples) {
  12495. return samples;
  12496. }
  12497. var gl = this._gl;
  12498. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12499. // Dispose previous render buffers
  12500. if (texture._depthStencilBuffer) {
  12501. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12502. texture._depthStencilBuffer = null;
  12503. }
  12504. if (texture._MSAAFramebuffer) {
  12505. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12506. texture._MSAAFramebuffer = null;
  12507. }
  12508. if (texture._MSAARenderBuffer) {
  12509. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12510. texture._MSAARenderBuffer = null;
  12511. }
  12512. if (samples > 1) {
  12513. var framebuffer = gl.createFramebuffer();
  12514. if (!framebuffer) {
  12515. throw new Error("Unable to create multi sampled framebuffer");
  12516. }
  12517. texture._MSAAFramebuffer = framebuffer;
  12518. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12519. var colorRenderbuffer = gl.createRenderbuffer();
  12520. if (!colorRenderbuffer) {
  12521. throw new Error("Unable to create multi sampled framebuffer");
  12522. }
  12523. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12524. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12525. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12526. texture._MSAARenderBuffer = colorRenderbuffer;
  12527. }
  12528. else {
  12529. this.bindUnboundFramebuffer(texture._framebuffer);
  12530. }
  12531. texture.samples = samples;
  12532. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12533. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12534. this.bindUnboundFramebuffer(null);
  12535. return samples;
  12536. };
  12537. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12538. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12539. return 1;
  12540. }
  12541. if (textures[0].samples === samples) {
  12542. return samples;
  12543. }
  12544. var gl = this._gl;
  12545. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12546. // Dispose previous render buffers
  12547. if (textures[0]._depthStencilBuffer) {
  12548. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12549. textures[0]._depthStencilBuffer = null;
  12550. }
  12551. if (textures[0]._MSAAFramebuffer) {
  12552. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12553. textures[0]._MSAAFramebuffer = null;
  12554. }
  12555. for (var i = 0; i < textures.length; i++) {
  12556. if (textures[i]._MSAARenderBuffer) {
  12557. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12558. textures[i]._MSAARenderBuffer = null;
  12559. }
  12560. }
  12561. if (samples > 1) {
  12562. var framebuffer = gl.createFramebuffer();
  12563. if (!framebuffer) {
  12564. throw new Error("Unable to create multi sampled framebuffer");
  12565. }
  12566. this.bindUnboundFramebuffer(framebuffer);
  12567. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12568. var attachments = [];
  12569. for (var i = 0; i < textures.length; i++) {
  12570. var texture = textures[i];
  12571. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12572. var colorRenderbuffer = gl.createRenderbuffer();
  12573. if (!colorRenderbuffer) {
  12574. throw new Error("Unable to create multi sampled framebuffer");
  12575. }
  12576. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12577. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12578. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12579. texture._MSAAFramebuffer = framebuffer;
  12580. texture._MSAARenderBuffer = colorRenderbuffer;
  12581. texture.samples = samples;
  12582. texture._depthStencilBuffer = depthStencilBuffer;
  12583. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12584. attachments.push(attachment);
  12585. }
  12586. gl.drawBuffers(attachments);
  12587. }
  12588. else {
  12589. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12590. }
  12591. this.bindUnboundFramebuffer(null);
  12592. return samples;
  12593. };
  12594. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12595. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12596. };
  12597. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12598. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12599. };
  12600. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12601. var gl = this._gl;
  12602. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12603. var generateMipMaps = true;
  12604. var generateDepthBuffer = true;
  12605. var generateStencilBuffer = false;
  12606. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12607. if (options !== undefined) {
  12608. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12609. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12610. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12611. if (options.samplingMode !== undefined) {
  12612. samplingMode = options.samplingMode;
  12613. }
  12614. }
  12615. texture.isCube = true;
  12616. texture.generateMipMaps = generateMipMaps;
  12617. texture.samples = 1;
  12618. texture.samplingMode = samplingMode;
  12619. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12620. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12621. for (var face = 0; face < 6; face++) {
  12622. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12623. }
  12624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12628. // Create the framebuffer
  12629. var framebuffer = gl.createFramebuffer();
  12630. this.bindUnboundFramebuffer(framebuffer);
  12631. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12632. // Mipmaps
  12633. if (texture.generateMipMaps) {
  12634. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12635. }
  12636. // Unbind
  12637. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12638. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12639. this.bindUnboundFramebuffer(null);
  12640. texture._framebuffer = framebuffer;
  12641. texture.width = size;
  12642. texture.height = size;
  12643. texture.isReady = true;
  12644. //this.resetTextureCache();
  12645. this._internalTexturesCache.push(texture);
  12646. return texture;
  12647. };
  12648. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12649. var _this = this;
  12650. if (onLoad === void 0) { onLoad = null; }
  12651. if (onError === void 0) { onError = null; }
  12652. if (forcedExtension === void 0) { forcedExtension = null; }
  12653. var callback = function (loadData) {
  12654. if (!loadData) {
  12655. if (onLoad) {
  12656. onLoad(null);
  12657. }
  12658. return;
  12659. }
  12660. var texture = loadData.texture;
  12661. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12662. texture._lodGenerationScale = scale;
  12663. texture._lodGenerationOffset = offset;
  12664. if (_this._caps.textureLOD) {
  12665. // Do not add extra process if texture lod is supported.
  12666. if (onLoad) {
  12667. onLoad(texture);
  12668. }
  12669. return;
  12670. }
  12671. var mipSlices = 3;
  12672. var gl = _this._gl;
  12673. var width = loadData.width;
  12674. if (!width) {
  12675. return;
  12676. }
  12677. var textures = [];
  12678. for (var i = 0; i < mipSlices; i++) {
  12679. //compute LOD from even spacing in smoothness (matching shader calculation)
  12680. var smoothness = i / (mipSlices - 1);
  12681. var roughness = 1 - smoothness;
  12682. var minLODIndex = offset; // roughness = 0
  12683. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12684. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12685. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12686. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12687. glTextureFromLod.isCube = true;
  12688. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12693. if (loadData.isDDS) {
  12694. var info = loadData.info;
  12695. var data = loadData.data;
  12696. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12697. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12698. }
  12699. else {
  12700. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12701. }
  12702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12703. // Wrap in a base texture for easy binding.
  12704. var lodTexture = new BABYLON.BaseTexture(scene);
  12705. lodTexture.isCube = true;
  12706. lodTexture._texture = glTextureFromLod;
  12707. glTextureFromLod.isReady = true;
  12708. textures.push(lodTexture);
  12709. }
  12710. texture._lodTextureHigh = textures[2];
  12711. texture._lodTextureMid = textures[1];
  12712. texture._lodTextureLow = textures[0];
  12713. if (onLoad) {
  12714. onLoad(texture);
  12715. }
  12716. };
  12717. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12718. };
  12719. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12720. var _this = this;
  12721. if (onLoad === void 0) { onLoad = null; }
  12722. if (onError === void 0) { onError = null; }
  12723. if (forcedExtension === void 0) { forcedExtension = null; }
  12724. var gl = this._gl;
  12725. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12726. texture.isCube = true;
  12727. texture.url = rootUrl;
  12728. texture.generateMipMaps = !noMipmap;
  12729. if (!this._doNotHandleContextLost) {
  12730. texture._extension = forcedExtension;
  12731. texture._files = files;
  12732. }
  12733. var isKTX = false;
  12734. var isDDS = false;
  12735. var lastDot = rootUrl.lastIndexOf('.');
  12736. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12737. if (this._textureFormatInUse) {
  12738. extension = this._textureFormatInUse;
  12739. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12740. isKTX = true;
  12741. }
  12742. else {
  12743. isDDS = (extension === ".dds");
  12744. }
  12745. var onerror = function (request, exception) {
  12746. if (onError && request) {
  12747. onError(request.status + " " + request.statusText, exception);
  12748. }
  12749. };
  12750. if (isKTX) {
  12751. this._loadFile(rootUrl, function (data) {
  12752. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12753. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12754. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12755. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12756. ktx.uploadLevels(_this._gl, !noMipmap);
  12757. _this.setCubeMapTextureParams(gl, loadMipmap);
  12758. texture.width = ktx.pixelWidth;
  12759. texture.height = ktx.pixelHeight;
  12760. texture.isReady = true;
  12761. }, undefined, undefined, true, onerror);
  12762. }
  12763. else if (isDDS) {
  12764. if (files && files.length === 6) {
  12765. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12766. var info;
  12767. var loadMipmap = false;
  12768. var width = 0;
  12769. for (var index = 0; index < imgs.length; index++) {
  12770. var data = imgs[index];
  12771. info = BABYLON.DDSTools.GetDDSInfo(data);
  12772. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12773. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12774. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12775. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12776. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12777. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12778. }
  12779. texture.width = info.width;
  12780. texture.height = info.height;
  12781. texture.type = info.textureType;
  12782. width = info.width;
  12783. }
  12784. _this.setCubeMapTextureParams(gl, loadMipmap);
  12785. texture.isReady = true;
  12786. if (onLoad) {
  12787. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12788. }
  12789. }, files, onError);
  12790. }
  12791. else {
  12792. this._loadFile(rootUrl, function (data) {
  12793. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12794. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12795. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12796. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12797. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12798. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12799. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12800. }
  12801. _this.setCubeMapTextureParams(gl, loadMipmap);
  12802. texture.width = info.width;
  12803. texture.height = info.height;
  12804. texture.isReady = true;
  12805. texture.type = info.textureType;
  12806. if (onLoad) {
  12807. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12808. }
  12809. }, undefined, undefined, true, onerror);
  12810. }
  12811. }
  12812. else {
  12813. if (!files) {
  12814. throw new Error("Cannot load cubemap because files were not defined");
  12815. }
  12816. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12817. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12818. var height = width;
  12819. _this._prepareWorkingCanvas();
  12820. if (!_this._workingCanvas || !_this._workingContext) {
  12821. return;
  12822. }
  12823. _this._workingCanvas.width = width;
  12824. _this._workingCanvas.height = height;
  12825. var faces = [
  12826. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12827. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12828. ];
  12829. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12830. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12831. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12832. for (var index = 0; index < faces.length; index++) {
  12833. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12834. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12835. }
  12836. if (!noMipmap) {
  12837. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12838. }
  12839. _this.setCubeMapTextureParams(gl, !noMipmap);
  12840. texture.width = width;
  12841. texture.height = height;
  12842. texture.isReady = true;
  12843. if (format) {
  12844. texture.format = format;
  12845. }
  12846. texture.onLoadedObservable.notifyObservers(texture);
  12847. texture.onLoadedObservable.clear();
  12848. if (onLoad) {
  12849. onLoad();
  12850. }
  12851. }, files, onError);
  12852. }
  12853. this._internalTexturesCache.push(texture);
  12854. return texture;
  12855. };
  12856. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12859. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12861. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12862. // this.resetTextureCache();
  12863. };
  12864. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12865. if (compression === void 0) { compression = null; }
  12866. if (level === void 0) { level = 0; }
  12867. texture._bufferViewArray = data;
  12868. texture.format = format;
  12869. texture.type = type;
  12870. texture.invertY = invertY;
  12871. texture._compression = compression;
  12872. var gl = this._gl;
  12873. var textureType = this._getWebGLTextureType(type);
  12874. var internalFormat = this._getInternalFormat(format);
  12875. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12876. var needConversion = false;
  12877. if (internalFormat === gl.RGB) {
  12878. internalFormat = gl.RGBA;
  12879. needConversion = true;
  12880. }
  12881. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12882. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12883. if (texture.width % 4 !== 0) {
  12884. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12885. }
  12886. // Data are known to be in +X +Y +Z -X -Y -Z
  12887. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12888. var faceData = data[faceIndex];
  12889. if (compression) {
  12890. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12891. }
  12892. else {
  12893. if (needConversion) {
  12894. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12895. }
  12896. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12897. }
  12898. }
  12899. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12900. if (isPot && texture.generateMipMaps && level === 0) {
  12901. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12902. }
  12903. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12904. // this.resetTextureCache();
  12905. texture.isReady = true;
  12906. };
  12907. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12908. if (compression === void 0) { compression = null; }
  12909. var gl = this._gl;
  12910. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12911. texture.isCube = true;
  12912. texture.generateMipMaps = generateMipMaps;
  12913. texture.format = format;
  12914. texture.type = type;
  12915. if (!this._doNotHandleContextLost) {
  12916. texture._bufferViewArray = data;
  12917. }
  12918. var textureType = this._getWebGLTextureType(type);
  12919. var internalFormat = this._getInternalFormat(format);
  12920. if (internalFormat === gl.RGB) {
  12921. internalFormat = gl.RGBA;
  12922. }
  12923. var width = size;
  12924. var height = width;
  12925. texture.width = width;
  12926. texture.height = height;
  12927. // Double check on POT to generate Mips.
  12928. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12929. if (!isPot) {
  12930. generateMipMaps = false;
  12931. }
  12932. // Upload data if needed. The texture won't be ready until then.
  12933. if (data) {
  12934. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12935. }
  12936. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12937. // Filters
  12938. if (data && generateMipMaps) {
  12939. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12940. }
  12941. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12944. }
  12945. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12946. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12947. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12948. }
  12949. else {
  12950. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12953. }
  12954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12956. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12957. return texture;
  12958. };
  12959. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12960. var _this = this;
  12961. if (onLoad === void 0) { onLoad = null; }
  12962. if (onError === void 0) { onError = null; }
  12963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12964. if (invertY === void 0) { invertY = false; }
  12965. var gl = this._gl;
  12966. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12967. scene._addPendingData(texture);
  12968. texture.url = url;
  12969. this._internalTexturesCache.push(texture);
  12970. var onerror = function (request, exception) {
  12971. scene._removePendingData(texture);
  12972. if (onError && request) {
  12973. onError(request.status + " " + request.statusText, exception);
  12974. }
  12975. };
  12976. var internalCallback = function (data) {
  12977. var width = texture.width;
  12978. var faceDataArrays = callback(data);
  12979. if (!faceDataArrays) {
  12980. return;
  12981. }
  12982. if (mipmmapGenerator) {
  12983. var textureType = _this._getWebGLTextureType(type);
  12984. var internalFormat = _this._getInternalFormat(format);
  12985. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12986. var needConversion = false;
  12987. if (internalFormat === gl.RGB) {
  12988. internalFormat = gl.RGBA;
  12989. needConversion = true;
  12990. }
  12991. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12992. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12993. var mipData = mipmmapGenerator(faceDataArrays);
  12994. for (var level = 0; level < mipData.length; level++) {
  12995. var mipSize = width >> level;
  12996. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12997. var mipFaceData = mipData[level][faceIndex];
  12998. if (needConversion) {
  12999. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13000. }
  13001. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13002. }
  13003. }
  13004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13005. }
  13006. else {
  13007. texture.generateMipMaps = !noMipmap;
  13008. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13009. }
  13010. texture.isReady = true;
  13011. // this.resetTextureCache();
  13012. scene._removePendingData(texture);
  13013. if (onLoad) {
  13014. onLoad();
  13015. }
  13016. };
  13017. this._loadFile(url, function (data) {
  13018. internalCallback(data);
  13019. }, undefined, scene.database, true, onerror);
  13020. return texture;
  13021. };
  13022. ;
  13023. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13024. if (compression === void 0) { compression = null; }
  13025. var internalFormat = this._getInternalFormat(format);
  13026. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13027. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13028. if (!this._doNotHandleContextLost) {
  13029. texture._bufferView = data;
  13030. texture.format = format;
  13031. texture.invertY = invertY;
  13032. texture._compression = compression;
  13033. }
  13034. if (texture.width % 4 !== 0) {
  13035. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13036. }
  13037. if (compression && data) {
  13038. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13039. }
  13040. else {
  13041. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13042. }
  13043. if (texture.generateMipMaps) {
  13044. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13045. }
  13046. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13047. // this.resetTextureCache();
  13048. texture.isReady = true;
  13049. };
  13050. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13051. if (compression === void 0) { compression = null; }
  13052. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13053. texture.baseWidth = width;
  13054. texture.baseHeight = height;
  13055. texture.baseDepth = depth;
  13056. texture.width = width;
  13057. texture.height = height;
  13058. texture.depth = depth;
  13059. texture.format = format;
  13060. texture.generateMipMaps = generateMipMaps;
  13061. texture.samplingMode = samplingMode;
  13062. texture.is3D = true;
  13063. if (!this._doNotHandleContextLost) {
  13064. texture._bufferView = data;
  13065. }
  13066. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13067. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13068. // Filters
  13069. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13070. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13071. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13072. if (generateMipMaps) {
  13073. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13074. }
  13075. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13076. this._internalTexturesCache.push(texture);
  13077. return texture;
  13078. };
  13079. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13080. var gl = this._gl;
  13081. if (!gl) {
  13082. return;
  13083. }
  13084. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13086. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13087. if (!noMipmap && !isCompressed) {
  13088. gl.generateMipmap(gl.TEXTURE_2D);
  13089. }
  13090. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13091. // this.resetTextureCache();
  13092. if (scene) {
  13093. scene._removePendingData(texture);
  13094. }
  13095. texture.onLoadedObservable.notifyObservers(texture);
  13096. texture.onLoadedObservable.clear();
  13097. };
  13098. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13099. var _this = this;
  13100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13101. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13102. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13103. var gl = this._gl;
  13104. if (!gl) {
  13105. return;
  13106. }
  13107. if (!texture._webGLTexture) {
  13108. // this.resetTextureCache();
  13109. if (scene) {
  13110. scene._removePendingData(texture);
  13111. }
  13112. return;
  13113. }
  13114. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13115. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13116. texture.baseWidth = width;
  13117. texture.baseHeight = height;
  13118. texture.width = potWidth;
  13119. texture.height = potHeight;
  13120. texture.isReady = true;
  13121. if (processFunction(potWidth, potHeight, function () {
  13122. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13123. })) {
  13124. // Returning as texture needs extra async steps
  13125. return;
  13126. }
  13127. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13128. };
  13129. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13130. // Create new RGBA data container.
  13131. var rgbaData;
  13132. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13133. rgbaData = new Float32Array(width * height * 4);
  13134. }
  13135. else {
  13136. rgbaData = new Uint32Array(width * height * 4);
  13137. }
  13138. // Convert each pixel.
  13139. for (var x = 0; x < width; x++) {
  13140. for (var y = 0; y < height; y++) {
  13141. var index = (y * width + x) * 3;
  13142. var newIndex = (y * width + x) * 4;
  13143. // Map Old Value to new value.
  13144. rgbaData[newIndex + 0] = rgbData[index + 0];
  13145. rgbaData[newIndex + 1] = rgbData[index + 1];
  13146. rgbaData[newIndex + 2] = rgbData[index + 2];
  13147. // Add fully opaque alpha channel.
  13148. rgbaData[newIndex + 3] = 1;
  13149. }
  13150. }
  13151. return rgbaData;
  13152. };
  13153. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13154. var gl = this._gl;
  13155. if (texture._framebuffer) {
  13156. gl.deleteFramebuffer(texture._framebuffer);
  13157. texture._framebuffer = null;
  13158. }
  13159. if (texture._depthStencilBuffer) {
  13160. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13161. texture._depthStencilBuffer = null;
  13162. }
  13163. if (texture._MSAAFramebuffer) {
  13164. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13165. texture._MSAAFramebuffer = null;
  13166. }
  13167. if (texture._MSAARenderBuffer) {
  13168. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13169. texture._MSAARenderBuffer = null;
  13170. }
  13171. };
  13172. Engine.prototype._releaseTexture = function (texture) {
  13173. var gl = this._gl;
  13174. this._releaseFramebufferObjects(texture);
  13175. gl.deleteTexture(texture._webGLTexture);
  13176. // Unbind channels
  13177. this.unbindAllTextures();
  13178. var index = this._internalTexturesCache.indexOf(texture);
  13179. if (index !== -1) {
  13180. this._internalTexturesCache.splice(index, 1);
  13181. }
  13182. // Integrated fixed lod samplers.
  13183. if (texture._lodTextureHigh) {
  13184. texture._lodTextureHigh.dispose();
  13185. }
  13186. if (texture._lodTextureMid) {
  13187. texture._lodTextureMid.dispose();
  13188. }
  13189. if (texture._lodTextureLow) {
  13190. texture._lodTextureLow.dispose();
  13191. }
  13192. };
  13193. Engine.prototype.setProgram = function (program) {
  13194. if (this._currentProgram !== program) {
  13195. this._gl.useProgram(program);
  13196. this._currentProgram = program;
  13197. }
  13198. };
  13199. Engine.prototype.bindSamplers = function (effect) {
  13200. this.setProgram(effect.getProgram());
  13201. var samplers = effect.getSamplers();
  13202. for (var index = 0; index < samplers.length; index++) {
  13203. var uniform = effect.getUniform(samplers[index]);
  13204. if (uniform) {
  13205. this._boundUniforms[index] = uniform;
  13206. }
  13207. }
  13208. this._currentEffect = null;
  13209. };
  13210. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13211. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13212. return;
  13213. }
  13214. // Remove
  13215. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13216. // Bind last to it
  13217. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13218. // Bind to dummy
  13219. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13220. };
  13221. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13222. if (!internalTexture) {
  13223. return -1;
  13224. }
  13225. internalTexture._initialSlot = channel;
  13226. if (this.disableTextureBindingOptimization) {
  13227. if (channel !== internalTexture._designatedSlot) {
  13228. this._textureCollisions.addCount(1, false);
  13229. }
  13230. }
  13231. else {
  13232. if (channel !== internalTexture._designatedSlot) {
  13233. if (internalTexture._designatedSlot > -1) {
  13234. return internalTexture._designatedSlot;
  13235. }
  13236. else {
  13237. // No slot for this texture, let's pick a new one (if we find a free slot)
  13238. if (this._nextFreeTextureSlots.length) {
  13239. return this._nextFreeTextureSlots[0];
  13240. }
  13241. // We need to recycle the oldest bound texture, sorry.
  13242. this._textureCollisions.addCount(1, false);
  13243. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13244. }
  13245. }
  13246. }
  13247. return channel;
  13248. };
  13249. Engine.prototype._linkTrackers = function (previous, next) {
  13250. previous.next = next;
  13251. next.previous = previous;
  13252. };
  13253. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13254. var currentSlot = internalTexture._designatedSlot;
  13255. if (currentSlot === -1) {
  13256. return -1;
  13257. }
  13258. internalTexture._designatedSlot = -1;
  13259. if (this.disableTextureBindingOptimization) {
  13260. return -1;
  13261. }
  13262. // Remove from bound list
  13263. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13264. // Free the slot
  13265. this._boundTexturesCache[currentSlot] = null;
  13266. this._nextFreeTextureSlots.push(currentSlot);
  13267. return currentSlot;
  13268. };
  13269. Engine.prototype._activateCurrentTexture = function () {
  13270. if (this._currentTextureChannel !== this._activeChannel) {
  13271. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13272. this._currentTextureChannel = this._activeChannel;
  13273. }
  13274. };
  13275. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13276. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13277. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13278. this._activeChannel = texture._designatedSlot;
  13279. }
  13280. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13281. var isTextureForRendering = texture && texture._initialSlot > -1;
  13282. if (currentTextureBound !== texture) {
  13283. if (currentTextureBound) {
  13284. this._removeDesignatedSlot(currentTextureBound);
  13285. }
  13286. this._activateCurrentTexture();
  13287. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13288. this._boundTexturesCache[this._activeChannel] = texture;
  13289. if (texture) {
  13290. if (!this.disableTextureBindingOptimization) {
  13291. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13292. if (slotIndex > -1) {
  13293. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13294. }
  13295. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13296. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13297. }
  13298. texture._designatedSlot = this._activeChannel;
  13299. }
  13300. }
  13301. else if (forTextureDataUpdate) {
  13302. this._activateCurrentTexture();
  13303. }
  13304. if (isTextureForRendering && !forTextureDataUpdate) {
  13305. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13306. }
  13307. };
  13308. Engine.prototype._bindTexture = function (channel, texture) {
  13309. if (channel < 0) {
  13310. return;
  13311. }
  13312. if (texture) {
  13313. channel = this._getCorrectTextureChannel(channel, texture);
  13314. }
  13315. this._activeChannel = channel;
  13316. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13317. };
  13318. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13319. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13320. };
  13321. Engine.prototype.unbindAllTextures = function () {
  13322. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13323. this._activeChannel = channel;
  13324. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13325. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13326. if (this.webGLVersion > 1) {
  13327. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13328. }
  13329. }
  13330. };
  13331. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13332. if (channel < 0) {
  13333. return;
  13334. }
  13335. if (uniform) {
  13336. this._boundUniforms[channel] = uniform;
  13337. }
  13338. this._setTexture(channel, texture);
  13339. };
  13340. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13341. var uniform = this._boundUniforms[sourceSlot];
  13342. if (uniform._currentState === destination) {
  13343. return;
  13344. }
  13345. this._gl.uniform1i(uniform, destination);
  13346. uniform._currentState = destination;
  13347. };
  13348. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13349. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13350. // Not ready?
  13351. if (!texture) {
  13352. if (this._boundTexturesCache[channel] != null) {
  13353. this._activeChannel = channel;
  13354. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13355. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13356. if (this.webGLVersion > 1) {
  13357. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13358. }
  13359. }
  13360. return false;
  13361. }
  13362. // Video
  13363. if (texture.video) {
  13364. this._activeChannel = channel;
  13365. texture.update();
  13366. }
  13367. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13368. texture.delayLoad();
  13369. return false;
  13370. }
  13371. var internalTexture;
  13372. if (texture.isReady()) {
  13373. internalTexture = texture.getInternalTexture();
  13374. }
  13375. else if (texture.isCube) {
  13376. internalTexture = this.emptyCubeTexture;
  13377. }
  13378. else if (texture.is3D) {
  13379. internalTexture = this.emptyTexture3D;
  13380. }
  13381. else {
  13382. internalTexture = this.emptyTexture;
  13383. }
  13384. if (!isPartOfTextureArray) {
  13385. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13386. }
  13387. if (this._boundTexturesCache[channel] === internalTexture) {
  13388. this._moveBoundTextureOnTop(internalTexture);
  13389. if (!isPartOfTextureArray) {
  13390. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13391. }
  13392. return false;
  13393. }
  13394. this._activeChannel = channel;
  13395. if (internalTexture && internalTexture.is3D) {
  13396. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13397. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13398. internalTexture._cachedWrapU = texture.wrapU;
  13399. switch (texture.wrapU) {
  13400. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13401. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13402. break;
  13403. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13404. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13405. break;
  13406. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13407. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13408. break;
  13409. }
  13410. }
  13411. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13412. internalTexture._cachedWrapV = texture.wrapV;
  13413. switch (texture.wrapV) {
  13414. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13415. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13416. break;
  13417. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13418. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13419. break;
  13420. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13421. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13422. break;
  13423. }
  13424. }
  13425. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13426. internalTexture._cachedWrapR = texture.wrapR;
  13427. switch (texture.wrapV) {
  13428. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13429. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13430. break;
  13431. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13432. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13433. break;
  13434. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13435. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13436. break;
  13437. }
  13438. }
  13439. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13440. }
  13441. else if (internalTexture && internalTexture.isCube) {
  13442. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13443. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13444. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13445. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13446. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13447. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13448. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13449. }
  13450. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13451. }
  13452. else {
  13453. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13454. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13455. internalTexture._cachedWrapU = texture.wrapU;
  13456. switch (texture.wrapU) {
  13457. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13458. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13459. break;
  13460. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13461. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13462. break;
  13463. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13464. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13465. break;
  13466. }
  13467. }
  13468. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13469. internalTexture._cachedWrapV = texture.wrapV;
  13470. switch (texture.wrapV) {
  13471. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13472. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13473. break;
  13474. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13475. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13476. break;
  13477. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13478. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13479. break;
  13480. }
  13481. }
  13482. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13483. }
  13484. return true;
  13485. };
  13486. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13487. if (channel < 0 || !uniform) {
  13488. return;
  13489. }
  13490. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13491. this._textureUnits = new Int32Array(textures.length);
  13492. }
  13493. for (var i = 0; i < textures.length; i++) {
  13494. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13495. }
  13496. this._gl.uniform1iv(uniform, this._textureUnits);
  13497. for (var index = 0; index < textures.length; index++) {
  13498. this._setTexture(this._textureUnits[index], textures[index], true);
  13499. }
  13500. };
  13501. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13502. var internalTexture = texture.getInternalTexture();
  13503. if (!internalTexture) {
  13504. return;
  13505. }
  13506. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13507. var value = texture.anisotropicFilteringLevel;
  13508. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13509. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13510. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13511. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13512. }
  13513. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13514. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13515. internalTexture._cachedAnisotropicFilteringLevel = value;
  13516. }
  13517. };
  13518. Engine.prototype.readPixels = function (x, y, width, height) {
  13519. var data = new Uint8Array(height * width * 4);
  13520. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13521. return data;
  13522. };
  13523. /**
  13524. * Add an externaly attached data from its key.
  13525. * This method call will fail and return false, if such key already exists.
  13526. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13527. * @param key the unique key that identifies the data
  13528. * @param data the data object to associate to the key for this Engine instance
  13529. * @return true if no such key were already present and the data was added successfully, false otherwise
  13530. */
  13531. Engine.prototype.addExternalData = function (key, data) {
  13532. if (!this._externalData) {
  13533. this._externalData = new BABYLON.StringDictionary();
  13534. }
  13535. return this._externalData.add(key, data);
  13536. };
  13537. /**
  13538. * Get an externaly attached data from its key
  13539. * @param key the unique key that identifies the data
  13540. * @return the associated data, if present (can be null), or undefined if not present
  13541. */
  13542. Engine.prototype.getExternalData = function (key) {
  13543. if (!this._externalData) {
  13544. this._externalData = new BABYLON.StringDictionary();
  13545. }
  13546. return this._externalData.get(key);
  13547. };
  13548. /**
  13549. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13550. * @param key the unique key that identifies the data
  13551. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13552. * @return the associated data, can be null if the factory returned null.
  13553. */
  13554. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13555. if (!this._externalData) {
  13556. this._externalData = new BABYLON.StringDictionary();
  13557. }
  13558. return this._externalData.getOrAddWithFactory(key, factory);
  13559. };
  13560. /**
  13561. * Remove an externaly attached data from the Engine instance
  13562. * @param key the unique key that identifies the data
  13563. * @return true if the data was successfully removed, false if it doesn't exist
  13564. */
  13565. Engine.prototype.removeExternalData = function (key) {
  13566. if (!this._externalData) {
  13567. this._externalData = new BABYLON.StringDictionary();
  13568. }
  13569. return this._externalData.remove(key);
  13570. };
  13571. Engine.prototype.unbindAllAttributes = function () {
  13572. if (this._mustWipeVertexAttributes) {
  13573. this._mustWipeVertexAttributes = false;
  13574. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13575. this._gl.disableVertexAttribArray(i);
  13576. this._vertexAttribArraysEnabled[i] = false;
  13577. this._currentBufferPointers[i].active = false;
  13578. }
  13579. return;
  13580. }
  13581. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13582. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13583. continue;
  13584. }
  13585. this._gl.disableVertexAttribArray(i);
  13586. this._vertexAttribArraysEnabled[i] = false;
  13587. this._currentBufferPointers[i].active = false;
  13588. }
  13589. };
  13590. Engine.prototype.releaseEffects = function () {
  13591. for (var name in this._compiledEffects) {
  13592. this._deleteProgram(this._compiledEffects[name]._program);
  13593. }
  13594. this._compiledEffects = {};
  13595. };
  13596. // Dispose
  13597. Engine.prototype.dispose = function () {
  13598. this.hideLoadingUI();
  13599. this.stopRenderLoop();
  13600. // Release postProcesses
  13601. while (this.postProcesses.length) {
  13602. this.postProcesses[0].dispose();
  13603. }
  13604. // Empty texture
  13605. if (this._emptyTexture) {
  13606. this._releaseTexture(this._emptyTexture);
  13607. this._emptyTexture = null;
  13608. }
  13609. if (this._emptyCubeTexture) {
  13610. this._releaseTexture(this._emptyCubeTexture);
  13611. this._emptyCubeTexture = null;
  13612. }
  13613. // Rescale PP
  13614. if (this._rescalePostProcess) {
  13615. this._rescalePostProcess.dispose();
  13616. }
  13617. // Release scenes
  13618. while (this.scenes.length) {
  13619. this.scenes[0].dispose();
  13620. }
  13621. // Release audio engine
  13622. if (Engine.audioEngine) {
  13623. Engine.audioEngine.dispose();
  13624. }
  13625. // Release effects
  13626. this.releaseEffects();
  13627. // Unbind
  13628. this.unbindAllAttributes();
  13629. if (this._dummyFramebuffer) {
  13630. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13631. }
  13632. //WebVR
  13633. this.disableVR();
  13634. // Events
  13635. if (BABYLON.Tools.IsWindowObjectExist()) {
  13636. window.removeEventListener("blur", this._onBlur);
  13637. window.removeEventListener("focus", this._onFocus);
  13638. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13639. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13640. if (this._renderingCanvas) {
  13641. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13642. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13643. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13644. if (!this._doNotHandleContextLost) {
  13645. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13646. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13647. }
  13648. }
  13649. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13650. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13651. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13652. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13653. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13654. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13655. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13656. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13657. if (this._onVrDisplayConnect) {
  13658. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13659. if (this._onVrDisplayDisconnect) {
  13660. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13661. }
  13662. if (this._onVrDisplayPresentChange) {
  13663. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13664. }
  13665. this._onVrDisplayConnect = null;
  13666. this._onVrDisplayDisconnect = null;
  13667. }
  13668. }
  13669. // Remove from Instances
  13670. var index = Engine.Instances.indexOf(this);
  13671. if (index >= 0) {
  13672. Engine.Instances.splice(index, 1);
  13673. }
  13674. this._workingCanvas = null;
  13675. this._workingContext = null;
  13676. this._currentBufferPointers = [];
  13677. this._renderingCanvas = null;
  13678. this._currentProgram = null;
  13679. this.onResizeObservable.clear();
  13680. this.onCanvasBlurObservable.clear();
  13681. this.onCanvasFocusObservable.clear();
  13682. this.onCanvasPointerOutObservable.clear();
  13683. this.onBeginFrameObservable.clear();
  13684. this.onEndFrameObservable.clear();
  13685. BABYLON.Effect.ResetCache();
  13686. // Abort active requests
  13687. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13688. var request = _a[_i];
  13689. request.abort();
  13690. }
  13691. };
  13692. // Loading screen
  13693. Engine.prototype.displayLoadingUI = function () {
  13694. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13695. return;
  13696. }
  13697. var loadingScreen = this.loadingScreen;
  13698. if (loadingScreen) {
  13699. loadingScreen.displayLoadingUI();
  13700. }
  13701. };
  13702. Engine.prototype.hideLoadingUI = function () {
  13703. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13704. return;
  13705. }
  13706. var loadingScreen = this.loadingScreen;
  13707. if (loadingScreen) {
  13708. loadingScreen.hideLoadingUI();
  13709. }
  13710. };
  13711. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13712. get: function () {
  13713. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13714. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13715. return this._loadingScreen;
  13716. },
  13717. set: function (loadingScreen) {
  13718. this._loadingScreen = loadingScreen;
  13719. },
  13720. enumerable: true,
  13721. configurable: true
  13722. });
  13723. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13724. set: function (text) {
  13725. this.loadingScreen.loadingUIText = text;
  13726. },
  13727. enumerable: true,
  13728. configurable: true
  13729. });
  13730. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13731. set: function (color) {
  13732. this.loadingScreen.loadingUIBackgroundColor = color;
  13733. },
  13734. enumerable: true,
  13735. configurable: true
  13736. });
  13737. Engine.prototype.attachContextLostEvent = function (callback) {
  13738. if (this._renderingCanvas) {
  13739. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13740. }
  13741. };
  13742. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13743. if (this._renderingCanvas) {
  13744. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13745. }
  13746. };
  13747. Engine.prototype.getVertexShaderSource = function (program) {
  13748. var shaders = this._gl.getAttachedShaders(program);
  13749. if (!shaders) {
  13750. return null;
  13751. }
  13752. return this._gl.getShaderSource(shaders[0]);
  13753. };
  13754. Engine.prototype.getFragmentShaderSource = function (program) {
  13755. var shaders = this._gl.getAttachedShaders(program);
  13756. if (!shaders) {
  13757. return null;
  13758. }
  13759. return this._gl.getShaderSource(shaders[1]);
  13760. };
  13761. Engine.prototype.getError = function () {
  13762. return this._gl.getError();
  13763. };
  13764. // FPS
  13765. Engine.prototype.getFps = function () {
  13766. return this._fps;
  13767. };
  13768. Engine.prototype.getDeltaTime = function () {
  13769. return this._deltaTime;
  13770. };
  13771. Engine.prototype._measureFps = function () {
  13772. this._performanceMonitor.sampleFrame();
  13773. this._fps = this._performanceMonitor.averageFPS;
  13774. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13775. };
  13776. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13777. if (faceIndex === void 0) { faceIndex = -1; }
  13778. var gl = this._gl;
  13779. if (!this._dummyFramebuffer) {
  13780. var dummy = gl.createFramebuffer();
  13781. if (!dummy) {
  13782. throw new Error("Unable to create dummy framebuffer");
  13783. }
  13784. this._dummyFramebuffer = dummy;
  13785. }
  13786. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13787. if (faceIndex > -1) {
  13788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13789. }
  13790. else {
  13791. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13792. }
  13793. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13794. var buffer;
  13795. switch (readType) {
  13796. case gl.UNSIGNED_BYTE:
  13797. buffer = new Uint8Array(4 * width * height);
  13798. readType = gl.UNSIGNED_BYTE;
  13799. break;
  13800. default:
  13801. buffer = new Float32Array(4 * width * height);
  13802. readType = gl.FLOAT;
  13803. break;
  13804. }
  13805. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13806. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13807. return buffer;
  13808. };
  13809. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13810. if (this._webGLVersion > 1) {
  13811. return this._caps.colorBufferFloat;
  13812. }
  13813. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13814. };
  13815. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13816. if (this._webGLVersion > 1) {
  13817. return this._caps.colorBufferFloat;
  13818. }
  13819. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13820. };
  13821. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13822. Engine.prototype._canRenderToFramebuffer = function (type) {
  13823. var gl = this._gl;
  13824. //clear existing errors
  13825. while (gl.getError() !== gl.NO_ERROR) { }
  13826. var successful = true;
  13827. var texture = gl.createTexture();
  13828. gl.bindTexture(gl.TEXTURE_2D, texture);
  13829. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13830. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13832. var fb = gl.createFramebuffer();
  13833. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13834. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13835. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13836. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13837. successful = successful && (gl.getError() === gl.NO_ERROR);
  13838. //try render by clearing frame buffer's color buffer
  13839. if (successful) {
  13840. gl.clear(gl.COLOR_BUFFER_BIT);
  13841. successful = successful && (gl.getError() === gl.NO_ERROR);
  13842. }
  13843. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13844. if (successful) {
  13845. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13846. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13847. var readFormat = gl.RGBA;
  13848. var readType = gl.UNSIGNED_BYTE;
  13849. var buffer = new Uint8Array(4);
  13850. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13851. successful = successful && (gl.getError() === gl.NO_ERROR);
  13852. }
  13853. //clean up
  13854. gl.deleteTexture(texture);
  13855. gl.deleteFramebuffer(fb);
  13856. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13857. //clear accumulated errors
  13858. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13859. return successful;
  13860. };
  13861. Engine.prototype._getWebGLTextureType = function (type) {
  13862. if (type === Engine.TEXTURETYPE_FLOAT) {
  13863. return this._gl.FLOAT;
  13864. }
  13865. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13866. // Add Half Float Constant.
  13867. return this._gl.HALF_FLOAT_OES;
  13868. }
  13869. return this._gl.UNSIGNED_BYTE;
  13870. };
  13871. ;
  13872. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13873. if (this._webGLVersion === 1) {
  13874. return this._gl.RGBA;
  13875. }
  13876. if (type === Engine.TEXTURETYPE_FLOAT) {
  13877. return this._gl.RGBA32F;
  13878. }
  13879. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13880. return this._gl.RGBA16F;
  13881. }
  13882. return this._gl.RGBA;
  13883. };
  13884. ;
  13885. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13886. if (type === Engine.TEXTURETYPE_FLOAT) {
  13887. return this._gl.RGBA32F;
  13888. }
  13889. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13890. return this._gl.RGBA16F;
  13891. }
  13892. return this._gl.RGBA8;
  13893. };
  13894. ;
  13895. Engine.prototype.createQuery = function () {
  13896. return this._gl.createQuery();
  13897. };
  13898. Engine.prototype.deleteQuery = function (query) {
  13899. this._gl.deleteQuery(query);
  13900. return this;
  13901. };
  13902. Engine.prototype.isQueryResultAvailable = function (query) {
  13903. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13904. };
  13905. Engine.prototype.getQueryResult = function (query) {
  13906. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13907. };
  13908. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13909. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13910. this._gl.beginQuery(glAlgorithm, query);
  13911. return this;
  13912. };
  13913. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13914. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13915. this._gl.endQuery(glAlgorithm);
  13916. return this;
  13917. };
  13918. /* Time queries */
  13919. Engine.prototype._createTimeQuery = function () {
  13920. var timerQuery = this._caps.timerQuery;
  13921. if (timerQuery.createQueryEXT) {
  13922. return timerQuery.createQueryEXT();
  13923. }
  13924. return this.createQuery();
  13925. };
  13926. Engine.prototype._deleteTimeQuery = function (query) {
  13927. var timerQuery = this._caps.timerQuery;
  13928. if (timerQuery.deleteQueryEXT) {
  13929. timerQuery.deleteQueryEXT(query);
  13930. return;
  13931. }
  13932. this.deleteQuery(query);
  13933. };
  13934. Engine.prototype._getTimeQueryResult = function (query) {
  13935. var timerQuery = this._caps.timerQuery;
  13936. if (timerQuery.getQueryObjectEXT) {
  13937. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13938. }
  13939. return this.getQueryResult(query);
  13940. };
  13941. Engine.prototype._getTimeQueryAvailability = function (query) {
  13942. var timerQuery = this._caps.timerQuery;
  13943. if (timerQuery.getQueryObjectEXT) {
  13944. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13945. }
  13946. return this.isQueryResultAvailable(query);
  13947. };
  13948. Engine.prototype.startTimeQuery = function () {
  13949. var timerQuery = this._caps.timerQuery;
  13950. if (!timerQuery) {
  13951. return null;
  13952. }
  13953. var token = new BABYLON._TimeToken();
  13954. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13955. if (this._caps.canUseTimestampForTimerQuery) {
  13956. token._startTimeQuery = this._createTimeQuery();
  13957. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13958. }
  13959. else {
  13960. if (this._currentNonTimestampToken) {
  13961. return this._currentNonTimestampToken;
  13962. }
  13963. token._timeElapsedQuery = this._createTimeQuery();
  13964. if (timerQuery.beginQueryEXT) {
  13965. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13966. }
  13967. else {
  13968. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13969. }
  13970. this._currentNonTimestampToken = token;
  13971. }
  13972. return token;
  13973. };
  13974. Engine.prototype.endTimeQuery = function (token) {
  13975. var timerQuery = this._caps.timerQuery;
  13976. if (!timerQuery || !token) {
  13977. return -1;
  13978. }
  13979. if (this._caps.canUseTimestampForTimerQuery) {
  13980. if (!token._startTimeQuery) {
  13981. return -1;
  13982. }
  13983. if (!token._endTimeQuery) {
  13984. token._endTimeQuery = this._createTimeQuery();
  13985. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13986. }
  13987. }
  13988. else if (!token._timeElapsedQueryEnded) {
  13989. if (!token._timeElapsedQuery) {
  13990. return -1;
  13991. }
  13992. if (timerQuery.endQueryEXT) {
  13993. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13994. }
  13995. else {
  13996. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13997. }
  13998. token._timeElapsedQueryEnded = true;
  13999. }
  14000. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14001. var available = false;
  14002. if (token._endTimeQuery) {
  14003. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14004. }
  14005. else if (token._timeElapsedQuery) {
  14006. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14007. }
  14008. if (available && !disjoint) {
  14009. var result = 0;
  14010. if (this._caps.canUseTimestampForTimerQuery) {
  14011. if (!token._startTimeQuery || !token._endTimeQuery) {
  14012. return -1;
  14013. }
  14014. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14015. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14016. result = timeEnd - timeStart;
  14017. this._deleteTimeQuery(token._startTimeQuery);
  14018. this._deleteTimeQuery(token._endTimeQuery);
  14019. token._startTimeQuery = null;
  14020. token._endTimeQuery = null;
  14021. }
  14022. else {
  14023. if (!token._timeElapsedQuery) {
  14024. return -1;
  14025. }
  14026. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14027. this._deleteTimeQuery(token._timeElapsedQuery);
  14028. token._timeElapsedQuery = null;
  14029. token._timeElapsedQueryEnded = false;
  14030. this._currentNonTimestampToken = null;
  14031. }
  14032. return result;
  14033. }
  14034. return -1;
  14035. };
  14036. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14037. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14038. };
  14039. // Transform feedback
  14040. Engine.prototype.createTransformFeedback = function () {
  14041. return this._gl.createTransformFeedback();
  14042. };
  14043. Engine.prototype.deleteTransformFeedback = function (value) {
  14044. this._gl.deleteTransformFeedback(value);
  14045. };
  14046. Engine.prototype.bindTransformFeedback = function (value) {
  14047. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14048. };
  14049. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14050. if (usePoints === void 0) { usePoints = true; }
  14051. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14052. };
  14053. Engine.prototype.endTransformFeedback = function () {
  14054. this._gl.endTransformFeedback();
  14055. };
  14056. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14057. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14058. };
  14059. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14060. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14061. };
  14062. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14063. var _this = this;
  14064. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14065. this._activeRequests.push(request);
  14066. request.onCompleteObservable.add(function (request) {
  14067. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14068. });
  14069. return request;
  14070. };
  14071. /** @ignore */
  14072. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14073. var _this = this;
  14074. return new Promise(function (resolve, reject) {
  14075. _this._loadFile(url, function (data) {
  14076. resolve(data);
  14077. }, undefined, database, useArrayBuffer, function (request, exception) {
  14078. reject(exception);
  14079. });
  14080. });
  14081. };
  14082. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14083. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14084. var onload = function (data) {
  14085. loadedFiles[index] = data;
  14086. loadedFiles._internalCount++;
  14087. if (loadedFiles._internalCount === 6) {
  14088. onfinish(loadedFiles);
  14089. }
  14090. };
  14091. var onerror = function (request, exception) {
  14092. if (onErrorCallBack && request) {
  14093. onErrorCallBack(request.status + " " + request.statusText, exception);
  14094. }
  14095. };
  14096. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14097. };
  14098. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14099. if (onError === void 0) { onError = null; }
  14100. var loadedFiles = [];
  14101. loadedFiles._internalCount = 0;
  14102. for (var index = 0; index < 6; index++) {
  14103. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14104. }
  14105. };
  14106. // Statics
  14107. Engine.isSupported = function () {
  14108. try {
  14109. var tempcanvas = document.createElement("canvas");
  14110. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14111. return gl != null && !!window.WebGLRenderingContext;
  14112. }
  14113. catch (e) {
  14114. return false;
  14115. }
  14116. };
  14117. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14118. Engine.ExceptionList = [
  14119. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14120. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14121. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14122. ];
  14123. Engine.Instances = new Array();
  14124. // Const statics
  14125. Engine._ALPHA_DISABLE = 0;
  14126. Engine._ALPHA_ADD = 1;
  14127. Engine._ALPHA_COMBINE = 2;
  14128. Engine._ALPHA_SUBTRACT = 3;
  14129. Engine._ALPHA_MULTIPLY = 4;
  14130. Engine._ALPHA_MAXIMIZED = 5;
  14131. Engine._ALPHA_ONEONE = 6;
  14132. Engine._ALPHA_PREMULTIPLIED = 7;
  14133. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14134. Engine._ALPHA_INTERPOLATE = 9;
  14135. Engine._ALPHA_SCREENMODE = 10;
  14136. Engine._DELAYLOADSTATE_NONE = 0;
  14137. Engine._DELAYLOADSTATE_LOADED = 1;
  14138. Engine._DELAYLOADSTATE_LOADING = 2;
  14139. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14140. Engine._TEXTUREFORMAT_ALPHA = 0;
  14141. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14142. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14143. Engine._TEXTUREFORMAT_RGB = 4;
  14144. Engine._TEXTUREFORMAT_RGBA = 5;
  14145. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14146. Engine._TEXTURETYPE_FLOAT = 1;
  14147. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14148. // Depht or Stencil test Constants.
  14149. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14150. 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.
  14151. 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.
  14152. 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.
  14153. 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.
  14154. 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.
  14155. 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.
  14156. 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.
  14157. // Stencil Actions Constants.
  14158. Engine._KEEP = 0x1E00;
  14159. Engine._REPLACE = 0x1E01;
  14160. Engine._INCR = 0x1E02;
  14161. Engine._DECR = 0x1E03;
  14162. Engine._INVERT = 0x150A;
  14163. Engine._INCR_WRAP = 0x8507;
  14164. Engine._DECR_WRAP = 0x8508;
  14165. // Texture rescaling mode
  14166. Engine._SCALEMODE_FLOOR = 1;
  14167. Engine._SCALEMODE_NEAREST = 2;
  14168. Engine._SCALEMODE_CEILING = 3;
  14169. // Updatable statics so stick with vars here
  14170. Engine.CollisionsEpsilon = 0.001;
  14171. Engine.CodeRepository = "src/";
  14172. Engine.ShadersRepository = "src/Shaders/";
  14173. return Engine;
  14174. }());
  14175. BABYLON.Engine = Engine;
  14176. })(BABYLON || (BABYLON = {}));
  14177. //# sourceMappingURL=babylon.engine.js.map
  14178. var BABYLON;
  14179. (function (BABYLON) {
  14180. /**
  14181. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14182. */
  14183. var Node = /** @class */ (function () {
  14184. /**
  14185. * @constructor
  14186. * @param {string} name - the name and id to be given to this node
  14187. * @param {BABYLON.Scene} the scene this node will be added to
  14188. */
  14189. function Node(name, scene) {
  14190. if (scene === void 0) { scene = null; }
  14191. this.state = "";
  14192. this.metadata = null;
  14193. this.doNotSerialize = false;
  14194. this.animations = new Array();
  14195. this._ranges = {};
  14196. this._isEnabled = true;
  14197. this._isReady = true;
  14198. this._currentRenderId = -1;
  14199. this._parentRenderId = -1;
  14200. /**
  14201. * An event triggered when the mesh is disposed.
  14202. * @type {BABYLON.Observable}
  14203. */
  14204. this.onDisposeObservable = new BABYLON.Observable();
  14205. // Behaviors
  14206. this._behaviors = new Array();
  14207. this.name = name;
  14208. this.id = name;
  14209. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14210. this.uniqueId = this._scene.getUniqueId();
  14211. this._initCache();
  14212. }
  14213. Object.defineProperty(Node.prototype, "parent", {
  14214. get: function () {
  14215. return this._parentNode;
  14216. },
  14217. set: function (parent) {
  14218. if (this._parentNode === parent) {
  14219. return;
  14220. }
  14221. // Remove self from list of children of parent
  14222. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14223. var index = this._parentNode._children.indexOf(this);
  14224. if (index !== -1) {
  14225. this._parentNode._children.splice(index, 1);
  14226. }
  14227. }
  14228. // Store new parent
  14229. this._parentNode = parent;
  14230. // Add as child to new parent
  14231. if (this._parentNode) {
  14232. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14233. this._parentNode._children = new Array();
  14234. }
  14235. this._parentNode._children.push(this);
  14236. }
  14237. },
  14238. enumerable: true,
  14239. configurable: true
  14240. });
  14241. Node.prototype.getClassName = function () {
  14242. return "Node";
  14243. };
  14244. Object.defineProperty(Node.prototype, "onDispose", {
  14245. set: function (callback) {
  14246. if (this._onDisposeObserver) {
  14247. this.onDisposeObservable.remove(this._onDisposeObserver);
  14248. }
  14249. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Node.prototype.getScene = function () {
  14255. return this._scene;
  14256. };
  14257. Node.prototype.getEngine = function () {
  14258. return this._scene.getEngine();
  14259. };
  14260. Node.prototype.addBehavior = function (behavior) {
  14261. var _this = this;
  14262. var index = this._behaviors.indexOf(behavior);
  14263. if (index !== -1) {
  14264. return this;
  14265. }
  14266. behavior.init();
  14267. if (this._scene.isLoading) {
  14268. // We defer the attach when the scene will be loaded
  14269. var observer = this._scene.onDataLoadedObservable.add(function () {
  14270. behavior.attach(_this);
  14271. setTimeout(function () {
  14272. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14273. _this._scene.onDataLoadedObservable.remove(observer);
  14274. }, 0);
  14275. });
  14276. }
  14277. else {
  14278. behavior.attach(this);
  14279. }
  14280. this._behaviors.push(behavior);
  14281. return this;
  14282. };
  14283. Node.prototype.removeBehavior = function (behavior) {
  14284. var index = this._behaviors.indexOf(behavior);
  14285. if (index === -1) {
  14286. return this;
  14287. }
  14288. this._behaviors[index].detach();
  14289. this._behaviors.splice(index, 1);
  14290. return this;
  14291. };
  14292. Object.defineProperty(Node.prototype, "behaviors", {
  14293. get: function () {
  14294. return this._behaviors;
  14295. },
  14296. enumerable: true,
  14297. configurable: true
  14298. });
  14299. Node.prototype.getBehaviorByName = function (name) {
  14300. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14301. var behavior = _a[_i];
  14302. if (behavior.name === name) {
  14303. return behavior;
  14304. }
  14305. }
  14306. return null;
  14307. };
  14308. // override it in derived class
  14309. Node.prototype.getWorldMatrix = function () {
  14310. return BABYLON.Matrix.Identity();
  14311. };
  14312. // override it in derived class if you add new variables to the cache
  14313. // and call the parent class method
  14314. Node.prototype._initCache = function () {
  14315. this._cache = {};
  14316. this._cache.parent = undefined;
  14317. };
  14318. Node.prototype.updateCache = function (force) {
  14319. if (!force && this.isSynchronized())
  14320. return;
  14321. this._cache.parent = this.parent;
  14322. this._updateCache();
  14323. };
  14324. // override it in derived class if you add new variables to the cache
  14325. // and call the parent class method if !ignoreParentClass
  14326. Node.prototype._updateCache = function (ignoreParentClass) {
  14327. };
  14328. // override it in derived class if you add new variables to the cache
  14329. Node.prototype._isSynchronized = function () {
  14330. return true;
  14331. };
  14332. Node.prototype._markSyncedWithParent = function () {
  14333. if (this.parent) {
  14334. this._parentRenderId = this.parent._currentRenderId;
  14335. }
  14336. };
  14337. Node.prototype.isSynchronizedWithParent = function () {
  14338. if (!this.parent) {
  14339. return true;
  14340. }
  14341. if (this._parentRenderId !== this.parent._currentRenderId) {
  14342. return false;
  14343. }
  14344. return this.parent.isSynchronized();
  14345. };
  14346. Node.prototype.isSynchronized = function (updateCache) {
  14347. var check = this.hasNewParent();
  14348. check = check || !this.isSynchronizedWithParent();
  14349. check = check || !this._isSynchronized();
  14350. if (updateCache)
  14351. this.updateCache(true);
  14352. return !check;
  14353. };
  14354. Node.prototype.hasNewParent = function (update) {
  14355. if (this._cache.parent === this.parent)
  14356. return false;
  14357. if (update)
  14358. this._cache.parent = this.parent;
  14359. return true;
  14360. };
  14361. /**
  14362. * Is this node ready to be used/rendered
  14363. * @return {boolean} is it ready
  14364. */
  14365. Node.prototype.isReady = function () {
  14366. return this._isReady;
  14367. };
  14368. /**
  14369. * Is this node enabled.
  14370. * 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.
  14371. * @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.
  14372. * @return {boolean} whether this node (and its parent) is enabled.
  14373. * @see setEnabled
  14374. */
  14375. Node.prototype.isEnabled = function (checkAncestors) {
  14376. if (checkAncestors === void 0) { checkAncestors = true; }
  14377. if (checkAncestors === false) {
  14378. return this._isEnabled;
  14379. }
  14380. if (this._isEnabled === false) {
  14381. return false;
  14382. }
  14383. if (this.parent !== undefined && this.parent !== null) {
  14384. return this.parent.isEnabled(checkAncestors);
  14385. }
  14386. return true;
  14387. };
  14388. /**
  14389. * Set the enabled state of this node.
  14390. * @param {boolean} value - the new enabled state
  14391. * @see isEnabled
  14392. */
  14393. Node.prototype.setEnabled = function (value) {
  14394. this._isEnabled = value;
  14395. };
  14396. /**
  14397. * Is this node a descendant of the given node.
  14398. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14399. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14400. * @see parent
  14401. */
  14402. Node.prototype.isDescendantOf = function (ancestor) {
  14403. if (this.parent) {
  14404. if (this.parent === ancestor) {
  14405. return true;
  14406. }
  14407. return this.parent.isDescendantOf(ancestor);
  14408. }
  14409. return false;
  14410. };
  14411. /**
  14412. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14413. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14414. * @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.
  14415. * @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.
  14416. */
  14417. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14418. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14419. if (!this._children) {
  14420. return;
  14421. }
  14422. for (var index = 0; index < this._children.length; index++) {
  14423. var item = this._children[index];
  14424. if (!predicate || predicate(item)) {
  14425. results.push(item);
  14426. }
  14427. if (!directDescendantsOnly) {
  14428. item._getDescendants(results, false, predicate);
  14429. }
  14430. }
  14431. };
  14432. /**
  14433. * Will return all nodes that have this node as ascendant.
  14434. * @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.
  14435. * @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.
  14436. * @return {BABYLON.Node[]} all children nodes of all types.
  14437. */
  14438. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14439. var results = new Array();
  14440. this._getDescendants(results, directDescendantsOnly, predicate);
  14441. return results;
  14442. };
  14443. /**
  14444. * Get all child-meshes of this node.
  14445. */
  14446. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14447. var results = [];
  14448. this._getDescendants(results, directDescendantsOnly, function (node) {
  14449. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14450. });
  14451. return results;
  14452. };
  14453. /**
  14454. * Get all child-transformNodes of this node.
  14455. */
  14456. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14457. var results = [];
  14458. this._getDescendants(results, directDescendantsOnly, function (node) {
  14459. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14460. });
  14461. return results;
  14462. };
  14463. /**
  14464. * Get all direct children of this node.
  14465. */
  14466. Node.prototype.getChildren = function (predicate) {
  14467. return this.getDescendants(true, predicate);
  14468. };
  14469. Node.prototype._setReady = function (state) {
  14470. if (state === this._isReady) {
  14471. return;
  14472. }
  14473. if (!state) {
  14474. this._isReady = false;
  14475. return;
  14476. }
  14477. this._isReady = true;
  14478. if (this.onReady) {
  14479. this.onReady(this);
  14480. }
  14481. };
  14482. Node.prototype.getAnimationByName = function (name) {
  14483. for (var i = 0; i < this.animations.length; i++) {
  14484. var animation = this.animations[i];
  14485. if (animation.name === name) {
  14486. return animation;
  14487. }
  14488. }
  14489. return null;
  14490. };
  14491. Node.prototype.createAnimationRange = function (name, from, to) {
  14492. // check name not already in use
  14493. if (!this._ranges[name]) {
  14494. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14495. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14496. if (this.animations[i]) {
  14497. this.animations[i].createRange(name, from, to);
  14498. }
  14499. }
  14500. }
  14501. };
  14502. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14503. if (deleteFrames === void 0) { deleteFrames = true; }
  14504. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14505. if (this.animations[i]) {
  14506. this.animations[i].deleteRange(name, deleteFrames);
  14507. }
  14508. }
  14509. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14510. };
  14511. Node.prototype.getAnimationRange = function (name) {
  14512. return this._ranges[name];
  14513. };
  14514. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14515. var range = this.getAnimationRange(name);
  14516. if (!range) {
  14517. return;
  14518. }
  14519. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14520. };
  14521. Node.prototype.serializeAnimationRanges = function () {
  14522. var serializationRanges = [];
  14523. for (var name in this._ranges) {
  14524. var localRange = this._ranges[name];
  14525. if (!localRange) {
  14526. continue;
  14527. }
  14528. var range = {};
  14529. range.name = name;
  14530. range.from = localRange.from;
  14531. range.to = localRange.to;
  14532. serializationRanges.push(range);
  14533. }
  14534. return serializationRanges;
  14535. };
  14536. // override it in derived class
  14537. Node.prototype.computeWorldMatrix = function (force) {
  14538. return BABYLON.Matrix.Identity();
  14539. };
  14540. Node.prototype.dispose = function () {
  14541. this.parent = null;
  14542. // Callback
  14543. this.onDisposeObservable.notifyObservers(this);
  14544. this.onDisposeObservable.clear();
  14545. // Behaviors
  14546. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14547. var behavior = _a[_i];
  14548. behavior.detach();
  14549. }
  14550. this._behaviors = [];
  14551. };
  14552. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14553. if (parsedNode.ranges) {
  14554. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14555. var data = parsedNode.ranges[index];
  14556. node.createAnimationRange(data.name, data.from, data.to);
  14557. }
  14558. }
  14559. };
  14560. __decorate([
  14561. BABYLON.serialize()
  14562. ], Node.prototype, "name", void 0);
  14563. __decorate([
  14564. BABYLON.serialize()
  14565. ], Node.prototype, "id", void 0);
  14566. __decorate([
  14567. BABYLON.serialize()
  14568. ], Node.prototype, "uniqueId", void 0);
  14569. __decorate([
  14570. BABYLON.serialize()
  14571. ], Node.prototype, "state", void 0);
  14572. __decorate([
  14573. BABYLON.serialize()
  14574. ], Node.prototype, "metadata", void 0);
  14575. return Node;
  14576. }());
  14577. BABYLON.Node = Node;
  14578. })(BABYLON || (BABYLON = {}));
  14579. //# sourceMappingURL=babylon.node.js.map
  14580. var BABYLON;
  14581. (function (BABYLON) {
  14582. var BoundingSphere = /** @class */ (function () {
  14583. function BoundingSphere(minimum, maximum) {
  14584. this.minimum = minimum;
  14585. this.maximum = maximum;
  14586. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14587. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14588. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14589. this.radius = distance * 0.5;
  14590. this.centerWorld = BABYLON.Vector3.Zero();
  14591. this._update(BABYLON.Matrix.Identity());
  14592. }
  14593. // Methods
  14594. BoundingSphere.prototype._update = function (world) {
  14595. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14596. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14597. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14598. };
  14599. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14600. for (var i = 0; i < 6; i++) {
  14601. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14602. return false;
  14603. }
  14604. return true;
  14605. };
  14606. BoundingSphere.prototype.intersectsPoint = function (point) {
  14607. var x = this.centerWorld.x - point.x;
  14608. var y = this.centerWorld.y - point.y;
  14609. var z = this.centerWorld.z - point.z;
  14610. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14611. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14612. return false;
  14613. return true;
  14614. };
  14615. // Statics
  14616. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14617. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14618. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14619. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14620. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14621. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14622. return false;
  14623. return true;
  14624. };
  14625. return BoundingSphere;
  14626. }());
  14627. BABYLON.BoundingSphere = BoundingSphere;
  14628. })(BABYLON || (BABYLON = {}));
  14629. //# sourceMappingURL=babylon.boundingSphere.js.map
  14630. var BABYLON;
  14631. (function (BABYLON) {
  14632. var BoundingBox = /** @class */ (function () {
  14633. function BoundingBox(minimum, maximum) {
  14634. this.minimum = minimum;
  14635. this.maximum = maximum;
  14636. this.vectors = new Array();
  14637. this.vectorsWorld = new Array();
  14638. // Bounding vectors
  14639. this.vectors.push(this.minimum.clone());
  14640. this.vectors.push(this.maximum.clone());
  14641. this.vectors.push(this.minimum.clone());
  14642. this.vectors[2].x = this.maximum.x;
  14643. this.vectors.push(this.minimum.clone());
  14644. this.vectors[3].y = this.maximum.y;
  14645. this.vectors.push(this.minimum.clone());
  14646. this.vectors[4].z = this.maximum.z;
  14647. this.vectors.push(this.maximum.clone());
  14648. this.vectors[5].z = this.minimum.z;
  14649. this.vectors.push(this.maximum.clone());
  14650. this.vectors[6].x = this.minimum.x;
  14651. this.vectors.push(this.maximum.clone());
  14652. this.vectors[7].y = this.minimum.y;
  14653. // OBB
  14654. this.center = this.maximum.add(this.minimum).scale(0.5);
  14655. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14656. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14657. // World
  14658. for (var index = 0; index < this.vectors.length; index++) {
  14659. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14660. }
  14661. this.minimumWorld = BABYLON.Vector3.Zero();
  14662. this.maximumWorld = BABYLON.Vector3.Zero();
  14663. this.centerWorld = BABYLON.Vector3.Zero();
  14664. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14665. this._update(BABYLON.Matrix.Identity());
  14666. }
  14667. // Methods
  14668. BoundingBox.prototype.getWorldMatrix = function () {
  14669. return this._worldMatrix;
  14670. };
  14671. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14672. this._worldMatrix.copyFrom(matrix);
  14673. return this;
  14674. };
  14675. BoundingBox.prototype._update = function (world) {
  14676. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14677. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14678. for (var index = 0; index < this.vectors.length; index++) {
  14679. var v = this.vectorsWorld[index];
  14680. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14681. if (v.x < this.minimumWorld.x)
  14682. this.minimumWorld.x = v.x;
  14683. if (v.y < this.minimumWorld.y)
  14684. this.minimumWorld.y = v.y;
  14685. if (v.z < this.minimumWorld.z)
  14686. this.minimumWorld.z = v.z;
  14687. if (v.x > this.maximumWorld.x)
  14688. this.maximumWorld.x = v.x;
  14689. if (v.y > this.maximumWorld.y)
  14690. this.maximumWorld.y = v.y;
  14691. if (v.z > this.maximumWorld.z)
  14692. this.maximumWorld.z = v.z;
  14693. }
  14694. // Extend
  14695. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14696. this.extendSizeWorld.scaleInPlace(0.5);
  14697. // OBB
  14698. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14699. this.centerWorld.scaleInPlace(0.5);
  14700. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14701. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14702. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14703. this._worldMatrix = world;
  14704. };
  14705. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14706. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14707. };
  14708. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14709. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14710. };
  14711. BoundingBox.prototype.intersectsPoint = function (point) {
  14712. var delta = -BABYLON.Epsilon;
  14713. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14714. return false;
  14715. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14716. return false;
  14717. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14718. return false;
  14719. return true;
  14720. };
  14721. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14722. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14723. };
  14724. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14725. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14726. return false;
  14727. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14728. return false;
  14729. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14730. return false;
  14731. return true;
  14732. };
  14733. // Statics
  14734. BoundingBox.Intersects = function (box0, box1) {
  14735. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14736. return false;
  14737. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14738. return false;
  14739. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14740. return false;
  14741. return true;
  14742. };
  14743. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14744. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14745. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14746. return (num <= (sphereRadius * sphereRadius));
  14747. };
  14748. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14749. for (var p = 0; p < 6; p++) {
  14750. for (var i = 0; i < 8; i++) {
  14751. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14752. return false;
  14753. }
  14754. }
  14755. }
  14756. return true;
  14757. };
  14758. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14759. for (var p = 0; p < 6; p++) {
  14760. var inCount = 8;
  14761. for (var i = 0; i < 8; i++) {
  14762. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14763. --inCount;
  14764. }
  14765. else {
  14766. break;
  14767. }
  14768. }
  14769. if (inCount === 0)
  14770. return false;
  14771. }
  14772. return true;
  14773. };
  14774. return BoundingBox;
  14775. }());
  14776. BABYLON.BoundingBox = BoundingBox;
  14777. })(BABYLON || (BABYLON = {}));
  14778. //# sourceMappingURL=babylon.boundingBox.js.map
  14779. var BABYLON;
  14780. (function (BABYLON) {
  14781. var computeBoxExtents = function (axis, box) {
  14782. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14783. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14784. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14785. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14786. var r = r0 + r1 + r2;
  14787. return {
  14788. min: p - r,
  14789. max: p + r
  14790. };
  14791. };
  14792. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14793. var axisOverlap = function (axis, box0, box1) {
  14794. var result0 = computeBoxExtents(axis, box0);
  14795. var result1 = computeBoxExtents(axis, box1);
  14796. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14797. };
  14798. var BoundingInfo = /** @class */ (function () {
  14799. function BoundingInfo(minimum, maximum) {
  14800. this.minimum = minimum;
  14801. this.maximum = maximum;
  14802. this._isLocked = false;
  14803. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14804. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14805. }
  14806. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14807. get: function () {
  14808. return this._isLocked;
  14809. },
  14810. set: function (value) {
  14811. this._isLocked = value;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. // Methods
  14817. BoundingInfo.prototype.update = function (world) {
  14818. if (this._isLocked) {
  14819. return;
  14820. }
  14821. this.boundingBox._update(world);
  14822. this.boundingSphere._update(world);
  14823. };
  14824. /**
  14825. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14826. * @param center New center of the bounding info
  14827. * @param extend New extend of the bounding info
  14828. */
  14829. BoundingInfo.prototype.centerOn = function (center, extend) {
  14830. this.minimum = center.subtract(extend);
  14831. this.maximum = center.add(extend);
  14832. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14833. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14834. return this;
  14835. };
  14836. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14837. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14838. return false;
  14839. return this.boundingBox.isInFrustum(frustumPlanes);
  14840. };
  14841. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14842. /**
  14843. * Gets the world distance between the min and max points of the bounding box
  14844. */
  14845. get: function () {
  14846. var boundingBox = this.boundingBox;
  14847. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14848. return size.length();
  14849. },
  14850. enumerable: true,
  14851. configurable: true
  14852. });
  14853. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14854. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14855. };
  14856. BoundingInfo.prototype._checkCollision = function (collider) {
  14857. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14858. };
  14859. BoundingInfo.prototype.intersectsPoint = function (point) {
  14860. if (!this.boundingSphere.centerWorld) {
  14861. return false;
  14862. }
  14863. if (!this.boundingSphere.intersectsPoint(point)) {
  14864. return false;
  14865. }
  14866. if (!this.boundingBox.intersectsPoint(point)) {
  14867. return false;
  14868. }
  14869. return true;
  14870. };
  14871. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14872. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14873. return false;
  14874. }
  14875. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14876. return false;
  14877. }
  14878. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14879. return false;
  14880. }
  14881. if (!precise) {
  14882. return true;
  14883. }
  14884. var box0 = this.boundingBox;
  14885. var box1 = boundingInfo.boundingBox;
  14886. if (!axisOverlap(box0.directions[0], box0, box1))
  14887. return false;
  14888. if (!axisOverlap(box0.directions[1], box0, box1))
  14889. return false;
  14890. if (!axisOverlap(box0.directions[2], box0, box1))
  14891. return false;
  14892. if (!axisOverlap(box1.directions[0], box0, box1))
  14893. return false;
  14894. if (!axisOverlap(box1.directions[1], box0, box1))
  14895. return false;
  14896. if (!axisOverlap(box1.directions[2], box0, box1))
  14897. return false;
  14898. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14899. return false;
  14900. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14901. return false;
  14902. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14903. return false;
  14904. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14905. return false;
  14906. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14907. return false;
  14908. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14909. return false;
  14910. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14911. return false;
  14912. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14913. return false;
  14914. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14915. return false;
  14916. return true;
  14917. };
  14918. return BoundingInfo;
  14919. }());
  14920. BABYLON.BoundingInfo = BoundingInfo;
  14921. })(BABYLON || (BABYLON = {}));
  14922. //# sourceMappingURL=babylon.boundingInfo.js.map
  14923. var BABYLON;
  14924. (function (BABYLON) {
  14925. var TransformNode = /** @class */ (function (_super) {
  14926. __extends(TransformNode, _super);
  14927. function TransformNode(name, scene, isPure) {
  14928. if (scene === void 0) { scene = null; }
  14929. if (isPure === void 0) { isPure = true; }
  14930. var _this = _super.call(this, name, scene) || this;
  14931. // Properties
  14932. _this._rotation = BABYLON.Vector3.Zero();
  14933. _this._scaling = BABYLON.Vector3.One();
  14934. _this._isDirty = false;
  14935. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14936. _this.scalingDeterminant = 1;
  14937. _this.infiniteDistance = false;
  14938. _this.position = BABYLON.Vector3.Zero();
  14939. _this._localWorld = BABYLON.Matrix.Zero();
  14940. _this._worldMatrix = BABYLON.Matrix.Zero();
  14941. _this._worldMatrixDeterminant = 0;
  14942. _this._absolutePosition = BABYLON.Vector3.Zero();
  14943. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14944. _this._postMultiplyPivotMatrix = false;
  14945. _this._isWorldMatrixFrozen = false;
  14946. /**
  14947. * An event triggered after the world matrix is updated
  14948. * @type {BABYLON.Observable}
  14949. */
  14950. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14951. _this._nonUniformScaling = false;
  14952. if (isPure) {
  14953. _this.getScene().addTransformNode(_this);
  14954. }
  14955. return _this;
  14956. }
  14957. Object.defineProperty(TransformNode.prototype, "rotation", {
  14958. /**
  14959. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14960. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14961. * Default : (0.0, 0.0, 0.0)
  14962. */
  14963. get: function () {
  14964. return this._rotation;
  14965. },
  14966. set: function (newRotation) {
  14967. this._rotation = newRotation;
  14968. },
  14969. enumerable: true,
  14970. configurable: true
  14971. });
  14972. Object.defineProperty(TransformNode.prototype, "scaling", {
  14973. /**
  14974. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14975. * Default : (1.0, 1.0, 1.0)
  14976. */
  14977. get: function () {
  14978. return this._scaling;
  14979. },
  14980. /**
  14981. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14982. * Default : (1.0, 1.0, 1.0)
  14983. */
  14984. set: function (newScaling) {
  14985. this._scaling = newScaling;
  14986. },
  14987. enumerable: true,
  14988. configurable: true
  14989. });
  14990. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14991. /**
  14992. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14993. * It's null by default.
  14994. * 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)
  14995. */
  14996. get: function () {
  14997. return this._rotationQuaternion;
  14998. },
  14999. set: function (quaternion) {
  15000. this._rotationQuaternion = quaternion;
  15001. //reset the rotation vector.
  15002. if (quaternion && this.rotation.length()) {
  15003. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15004. }
  15005. },
  15006. enumerable: true,
  15007. configurable: true
  15008. });
  15009. /**
  15010. * Returns the latest update of the World matrix
  15011. * Returns a Matrix.
  15012. */
  15013. TransformNode.prototype.getWorldMatrix = function () {
  15014. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15015. this.computeWorldMatrix();
  15016. }
  15017. return this._worldMatrix;
  15018. };
  15019. /**
  15020. * Returns the latest update of the World matrix determinant.
  15021. */
  15022. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15023. return this._worldMatrixDeterminant;
  15024. };
  15025. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15026. /**
  15027. * Returns directly the latest state of the mesh World matrix.
  15028. * A Matrix is returned.
  15029. */
  15030. get: function () {
  15031. return this._worldMatrix;
  15032. },
  15033. enumerable: true,
  15034. configurable: true
  15035. });
  15036. /**
  15037. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15038. * Returns the AbstractMesh.
  15039. */
  15040. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15041. this._poseMatrix.copyFrom(matrix);
  15042. return this;
  15043. };
  15044. /**
  15045. * Returns the mesh Pose matrix.
  15046. * Returned object : Matrix
  15047. */
  15048. TransformNode.prototype.getPoseMatrix = function () {
  15049. return this._poseMatrix;
  15050. };
  15051. TransformNode.prototype._isSynchronized = function () {
  15052. if (this._isDirty) {
  15053. return false;
  15054. }
  15055. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15056. return false;
  15057. if (this._cache.pivotMatrixUpdated) {
  15058. return false;
  15059. }
  15060. if (this.infiniteDistance) {
  15061. return false;
  15062. }
  15063. if (!this._cache.position.equals(this.position))
  15064. return false;
  15065. if (this.rotationQuaternion) {
  15066. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15067. return false;
  15068. }
  15069. if (!this._cache.rotation.equals(this.rotation))
  15070. return false;
  15071. if (!this._cache.scaling.equals(this.scaling))
  15072. return false;
  15073. return true;
  15074. };
  15075. TransformNode.prototype._initCache = function () {
  15076. _super.prototype._initCache.call(this);
  15077. this._cache.localMatrixUpdated = false;
  15078. this._cache.position = BABYLON.Vector3.Zero();
  15079. this._cache.scaling = BABYLON.Vector3.Zero();
  15080. this._cache.rotation = BABYLON.Vector3.Zero();
  15081. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15082. this._cache.billboardMode = -1;
  15083. };
  15084. TransformNode.prototype.markAsDirty = function (property) {
  15085. if (property === "rotation") {
  15086. this.rotationQuaternion = null;
  15087. }
  15088. this._currentRenderId = Number.MAX_VALUE;
  15089. this._isDirty = true;
  15090. return this;
  15091. };
  15092. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15093. /**
  15094. * Returns the current mesh absolute position.
  15095. * Retuns a Vector3.
  15096. */
  15097. get: function () {
  15098. return this._absolutePosition;
  15099. },
  15100. enumerable: true,
  15101. configurable: true
  15102. });
  15103. /**
  15104. * Sets a new pivot matrix to the mesh.
  15105. * Returns the AbstractMesh.
  15106. */
  15107. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15108. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  15109. this._pivotMatrix = matrix.clone();
  15110. this._cache.pivotMatrixUpdated = true;
  15111. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15112. if (!this._pivotMatrixInverse) {
  15113. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15114. }
  15115. else {
  15116. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15117. }
  15118. return this;
  15119. };
  15120. /**
  15121. * Returns the mesh pivot matrix.
  15122. * Default : Identity.
  15123. * A Matrix is returned.
  15124. */
  15125. TransformNode.prototype.getPivotMatrix = function () {
  15126. return this._pivotMatrix;
  15127. };
  15128. /**
  15129. * Prevents the World matrix to be computed any longer.
  15130. * Returns the AbstractMesh.
  15131. */
  15132. TransformNode.prototype.freezeWorldMatrix = function () {
  15133. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15134. this.computeWorldMatrix(true);
  15135. this._isWorldMatrixFrozen = true;
  15136. return this;
  15137. };
  15138. /**
  15139. * Allows back the World matrix computation.
  15140. * Returns the AbstractMesh.
  15141. */
  15142. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15143. this._isWorldMatrixFrozen = false;
  15144. this.computeWorldMatrix(true);
  15145. return this;
  15146. };
  15147. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15148. /**
  15149. * True if the World matrix has been frozen.
  15150. * Returns a boolean.
  15151. */
  15152. get: function () {
  15153. return this._isWorldMatrixFrozen;
  15154. },
  15155. enumerable: true,
  15156. configurable: true
  15157. });
  15158. /**
  15159. * Retuns the mesh absolute position in the World.
  15160. * Returns a Vector3.
  15161. */
  15162. TransformNode.prototype.getAbsolutePosition = function () {
  15163. this.computeWorldMatrix();
  15164. return this._absolutePosition;
  15165. };
  15166. /**
  15167. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15168. * Returns the AbstractMesh.
  15169. */
  15170. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15171. if (!absolutePosition) {
  15172. return this;
  15173. }
  15174. var absolutePositionX;
  15175. var absolutePositionY;
  15176. var absolutePositionZ;
  15177. if (absolutePosition.x === undefined) {
  15178. if (arguments.length < 3) {
  15179. return this;
  15180. }
  15181. absolutePositionX = arguments[0];
  15182. absolutePositionY = arguments[1];
  15183. absolutePositionZ = arguments[2];
  15184. }
  15185. else {
  15186. absolutePositionX = absolutePosition.x;
  15187. absolutePositionY = absolutePosition.y;
  15188. absolutePositionZ = absolutePosition.z;
  15189. }
  15190. if (this.parent) {
  15191. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15192. invertParentWorldMatrix.invert();
  15193. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15194. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15195. }
  15196. else {
  15197. this.position.x = absolutePositionX;
  15198. this.position.y = absolutePositionY;
  15199. this.position.z = absolutePositionZ;
  15200. }
  15201. return this;
  15202. };
  15203. /**
  15204. * Sets the mesh position in its local space.
  15205. * Returns the AbstractMesh.
  15206. */
  15207. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15208. this.computeWorldMatrix();
  15209. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15210. return this;
  15211. };
  15212. /**
  15213. * Returns the mesh position in the local space from the current World matrix values.
  15214. * Returns a new Vector3.
  15215. */
  15216. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15217. this.computeWorldMatrix();
  15218. var invLocalWorldMatrix = this._localWorld.clone();
  15219. invLocalWorldMatrix.invert();
  15220. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15221. };
  15222. /**
  15223. * Translates the mesh along the passed Vector3 in its local space.
  15224. * Returns the AbstractMesh.
  15225. */
  15226. TransformNode.prototype.locallyTranslate = function (vector3) {
  15227. this.computeWorldMatrix(true);
  15228. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15229. return this;
  15230. };
  15231. /**
  15232. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15233. * @param targetPoint the position (must be in same space as current mesh) to look at
  15234. * @param yawCor optional yaw (y-axis) correction in radians
  15235. * @param pitchCor optional pitch (x-axis) correction in radians
  15236. * @param rollCor optional roll (z-axis) correction in radians
  15237. * @param space the choosen space of the target
  15238. * @returns the TransformNode.
  15239. */
  15240. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15241. if (yawCor === void 0) { yawCor = 0; }
  15242. if (pitchCor === void 0) { pitchCor = 0; }
  15243. if (rollCor === void 0) { rollCor = 0; }
  15244. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15245. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15246. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15247. targetPoint.subtractToRef(pos, dv);
  15248. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15249. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15250. var pitch = Math.atan2(dv.y, len);
  15251. if (this.rotationQuaternion) {
  15252. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15253. }
  15254. else {
  15255. this.rotation.x = pitch + pitchCor;
  15256. this.rotation.y = yaw + yawCor;
  15257. this.rotation.z = rollCor;
  15258. }
  15259. return this;
  15260. };
  15261. /**
  15262. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15263. * This Vector3 is expressed in the World space.
  15264. */
  15265. TransformNode.prototype.getDirection = function (localAxis) {
  15266. var result = BABYLON.Vector3.Zero();
  15267. this.getDirectionToRef(localAxis, result);
  15268. return result;
  15269. };
  15270. /**
  15271. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15272. * localAxis is expressed in the mesh local space.
  15273. * result is computed in the Wordl space from the mesh World matrix.
  15274. * Returns the AbstractMesh.
  15275. */
  15276. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15277. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15278. return this;
  15279. };
  15280. TransformNode.prototype.setPivotPoint = function (point, space) {
  15281. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15282. if (this.getScene().getRenderId() == 0) {
  15283. this.computeWorldMatrix(true);
  15284. }
  15285. var wm = this.getWorldMatrix();
  15286. if (space == BABYLON.Space.WORLD) {
  15287. var tmat = BABYLON.Tmp.Matrix[0];
  15288. wm.invertToRef(tmat);
  15289. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15290. }
  15291. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15292. this._pivotMatrix.m[12] = -point.x;
  15293. this._pivotMatrix.m[13] = -point.y;
  15294. this._pivotMatrix.m[14] = -point.z;
  15295. if (!this._pivotMatrixInverse) {
  15296. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15297. }
  15298. else {
  15299. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15300. }
  15301. this._cache.pivotMatrixUpdated = true;
  15302. return this;
  15303. };
  15304. /**
  15305. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15306. */
  15307. TransformNode.prototype.getPivotPoint = function () {
  15308. var point = BABYLON.Vector3.Zero();
  15309. this.getPivotPointToRef(point);
  15310. return point;
  15311. };
  15312. /**
  15313. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15314. * Returns the AbstractMesh.
  15315. */
  15316. TransformNode.prototype.getPivotPointToRef = function (result) {
  15317. result.x = -this._pivotMatrix.m[12];
  15318. result.y = -this._pivotMatrix.m[13];
  15319. result.z = -this._pivotMatrix.m[14];
  15320. return this;
  15321. };
  15322. /**
  15323. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15324. */
  15325. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15326. var point = BABYLON.Vector3.Zero();
  15327. this.getAbsolutePivotPointToRef(point);
  15328. return point;
  15329. };
  15330. /**
  15331. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15332. * Returns the AbstractMesh.
  15333. */
  15334. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15335. result.x = this._pivotMatrix.m[12];
  15336. result.y = this._pivotMatrix.m[13];
  15337. result.z = this._pivotMatrix.m[14];
  15338. this.getPivotPointToRef(result);
  15339. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15340. return this;
  15341. };
  15342. /**
  15343. * Defines the passed node as the parent of the current node.
  15344. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15345. * Returns the TransformNode.
  15346. */
  15347. TransformNode.prototype.setParent = function (node) {
  15348. if (node === null) {
  15349. var rotation = BABYLON.Tmp.Quaternion[0];
  15350. var position = BABYLON.Tmp.Vector3[0];
  15351. var scale = BABYLON.Tmp.Vector3[1];
  15352. if (this.parent && this.parent.computeWorldMatrix) {
  15353. this.parent.computeWorldMatrix(true);
  15354. }
  15355. this.computeWorldMatrix(true);
  15356. this.getWorldMatrix().decompose(scale, rotation, position);
  15357. if (this.rotationQuaternion) {
  15358. this.rotationQuaternion.copyFrom(rotation);
  15359. }
  15360. else {
  15361. rotation.toEulerAnglesToRef(this.rotation);
  15362. }
  15363. this.scaling.x = scale.x;
  15364. this.scaling.y = scale.y;
  15365. this.scaling.z = scale.z;
  15366. this.position.x = position.x;
  15367. this.position.y = position.y;
  15368. this.position.z = position.z;
  15369. }
  15370. else {
  15371. var rotation = BABYLON.Tmp.Quaternion[0];
  15372. var position = BABYLON.Tmp.Vector3[0];
  15373. var scale = BABYLON.Tmp.Vector3[1];
  15374. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15375. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15376. this.computeWorldMatrix(true);
  15377. node.computeWorldMatrix(true);
  15378. node.getWorldMatrix().invertToRef(invParentMatrix);
  15379. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15380. diffMatrix.decompose(scale, rotation, position);
  15381. if (this.rotationQuaternion) {
  15382. this.rotationQuaternion.copyFrom(rotation);
  15383. }
  15384. else {
  15385. rotation.toEulerAnglesToRef(this.rotation);
  15386. }
  15387. this.position.x = position.x;
  15388. this.position.y = position.y;
  15389. this.position.z = position.z;
  15390. this.scaling.x = scale.x;
  15391. this.scaling.y = scale.y;
  15392. this.scaling.z = scale.z;
  15393. }
  15394. this.parent = node;
  15395. return this;
  15396. };
  15397. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15398. get: function () {
  15399. return this._nonUniformScaling;
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15405. if (this._nonUniformScaling === value) {
  15406. return false;
  15407. }
  15408. this._nonUniformScaling = true;
  15409. return true;
  15410. };
  15411. /**
  15412. * Attach the current TransformNode to another TransformNode associated with a bone
  15413. * @param bone Bone affecting the TransformNode
  15414. * @param affectedTransformNode TransformNode associated with the bone
  15415. */
  15416. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15417. this._transformToBoneReferal = affectedTransformNode;
  15418. this.parent = bone;
  15419. if (bone.getWorldMatrix().determinant() < 0) {
  15420. this.scalingDeterminant *= -1;
  15421. }
  15422. return this;
  15423. };
  15424. TransformNode.prototype.detachFromBone = function () {
  15425. if (!this.parent) {
  15426. return this;
  15427. }
  15428. if (this.parent.getWorldMatrix().determinant() < 0) {
  15429. this.scalingDeterminant *= -1;
  15430. }
  15431. this._transformToBoneReferal = null;
  15432. this.parent = null;
  15433. return this;
  15434. };
  15435. /**
  15436. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15437. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15438. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15439. * The passed axis is also normalized.
  15440. * Returns the AbstractMesh.
  15441. */
  15442. TransformNode.prototype.rotate = function (axis, amount, space) {
  15443. axis.normalize();
  15444. if (!this.rotationQuaternion) {
  15445. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15446. this.rotation = BABYLON.Vector3.Zero();
  15447. }
  15448. var rotationQuaternion;
  15449. if (!space || space === BABYLON.Space.LOCAL) {
  15450. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15451. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15452. }
  15453. else {
  15454. if (this.parent) {
  15455. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15456. invertParentWorldMatrix.invert();
  15457. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15458. }
  15459. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15460. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15461. }
  15462. return this;
  15463. };
  15464. /**
  15465. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15466. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15467. * The passed axis is also normalized.
  15468. * Returns the AbstractMesh.
  15469. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15470. */
  15471. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15472. axis.normalize();
  15473. if (!this.rotationQuaternion) {
  15474. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15475. this.rotation.copyFromFloats(0, 0, 0);
  15476. }
  15477. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15478. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15479. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15480. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15481. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15482. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15483. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15484. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15485. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15486. return this;
  15487. };
  15488. /**
  15489. * Translates the mesh along the axis vector for the passed distance in the given space.
  15490. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15491. * Returns the AbstractMesh.
  15492. */
  15493. TransformNode.prototype.translate = function (axis, distance, space) {
  15494. var displacementVector = axis.scale(distance);
  15495. if (!space || space === BABYLON.Space.LOCAL) {
  15496. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15497. this.setPositionWithLocalVector(tempV3);
  15498. }
  15499. else {
  15500. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15501. }
  15502. return this;
  15503. };
  15504. /**
  15505. * Adds a rotation step to the mesh current rotation.
  15506. * x, y, z are Euler angles expressed in radians.
  15507. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15508. * This means this rotation is made in the mesh local space only.
  15509. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15510. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15511. * ```javascript
  15512. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15513. * ```
  15514. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15515. * 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.
  15516. * Returns the AbstractMesh.
  15517. */
  15518. TransformNode.prototype.addRotation = function (x, y, z) {
  15519. var rotationQuaternion;
  15520. if (this.rotationQuaternion) {
  15521. rotationQuaternion = this.rotationQuaternion;
  15522. }
  15523. else {
  15524. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15525. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15526. }
  15527. var accumulation = BABYLON.Tmp.Quaternion[0];
  15528. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15529. rotationQuaternion.multiplyInPlace(accumulation);
  15530. if (!this.rotationQuaternion) {
  15531. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15532. }
  15533. return this;
  15534. };
  15535. /**
  15536. * Computes the mesh World matrix and returns it.
  15537. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15538. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15539. * If the parameter `force`is set to `true`, the actual computation is done.
  15540. * Returns the mesh World Matrix.
  15541. */
  15542. TransformNode.prototype.computeWorldMatrix = function (force) {
  15543. if (this._isWorldMatrixFrozen) {
  15544. return this._worldMatrix;
  15545. }
  15546. if (!force && this.isSynchronized(true)) {
  15547. return this._worldMatrix;
  15548. }
  15549. this._cache.position.copyFrom(this.position);
  15550. this._cache.scaling.copyFrom(this.scaling);
  15551. this._cache.pivotMatrixUpdated = false;
  15552. this._cache.billboardMode = this.billboardMode;
  15553. this._currentRenderId = this.getScene().getRenderId();
  15554. this._isDirty = false;
  15555. // Scaling
  15556. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15557. // Rotation
  15558. //rotate, if quaternion is set and rotation was used
  15559. if (this.rotationQuaternion) {
  15560. var len = this.rotation.length();
  15561. if (len) {
  15562. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15563. this.rotation.copyFromFloats(0, 0, 0);
  15564. }
  15565. }
  15566. if (this.rotationQuaternion) {
  15567. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15568. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15569. }
  15570. else {
  15571. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15572. this._cache.rotation.copyFrom(this.rotation);
  15573. }
  15574. // Translation
  15575. var camera = this.getScene().activeCamera;
  15576. if (this.infiniteDistance && !this.parent && camera) {
  15577. var cameraWorldMatrix = camera.getWorldMatrix();
  15578. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15579. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15580. }
  15581. else {
  15582. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15583. }
  15584. // Composing transformations
  15585. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15586. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15587. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15588. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15589. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15590. // Need to decompose each rotation here
  15591. var currentPosition = BABYLON.Tmp.Vector3[3];
  15592. if (this.parent && this.parent.getWorldMatrix) {
  15593. if (this._transformToBoneReferal) {
  15594. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15595. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15596. }
  15597. else {
  15598. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15599. }
  15600. }
  15601. else {
  15602. currentPosition.copyFrom(this.position);
  15603. }
  15604. currentPosition.subtractInPlace(camera.globalPosition);
  15605. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15606. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15607. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15608. }
  15609. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15610. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15611. }
  15612. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15613. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15614. }
  15615. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15616. }
  15617. else {
  15618. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15619. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15620. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15621. }
  15622. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15623. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15624. }
  15625. // Local world
  15626. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15627. // Parent
  15628. if (this.parent && this.parent.getWorldMatrix) {
  15629. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15630. if (this._transformToBoneReferal) {
  15631. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15632. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15633. }
  15634. else {
  15635. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15636. }
  15637. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15638. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15639. this._worldMatrix.copyFrom(this._localWorld);
  15640. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15641. }
  15642. else {
  15643. if (this._transformToBoneReferal) {
  15644. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15645. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15646. }
  15647. else {
  15648. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15649. }
  15650. }
  15651. this._markSyncedWithParent();
  15652. }
  15653. else {
  15654. this._worldMatrix.copyFrom(this._localWorld);
  15655. }
  15656. // Post multiply inverse of pivotMatrix
  15657. if (this._postMultiplyPivotMatrix) {
  15658. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15659. }
  15660. // Normal matrix
  15661. if (this.scaling.isNonUniform) {
  15662. this._updateNonUniformScalingState(true);
  15663. }
  15664. else if (this.parent && this.parent._nonUniformScaling) {
  15665. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15666. }
  15667. else {
  15668. this._updateNonUniformScalingState(false);
  15669. }
  15670. this._afterComputeWorldMatrix();
  15671. // Absolute position
  15672. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15673. if (this._pivotMatrixInverse) {
  15674. BABYLON.Vector3.TransformCoordinatesToRef(this._absolutePosition, this._pivotMatrixInverse, this._absolutePosition);
  15675. }
  15676. // Callbacks
  15677. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15678. if (!this._poseMatrix) {
  15679. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15680. }
  15681. // Cache the determinant
  15682. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15683. return this._worldMatrix;
  15684. };
  15685. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15686. };
  15687. /**
  15688. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15689. * @param func: callback function to add
  15690. *
  15691. * Returns the TransformNode.
  15692. */
  15693. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15694. this.onAfterWorldMatrixUpdateObservable.add(func);
  15695. return this;
  15696. };
  15697. /**
  15698. * Removes a registered callback function.
  15699. * Returns the TransformNode.
  15700. */
  15701. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15702. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15703. return this;
  15704. };
  15705. /**
  15706. * Clone the current transform node
  15707. * Returns the new transform node
  15708. * @param name Name of the new clone
  15709. * @param newParent New parent for the clone
  15710. * @param doNotCloneChildren Do not clone children hierarchy
  15711. */
  15712. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15713. var _this = this;
  15714. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15715. result.name = name;
  15716. result.id = name;
  15717. if (newParent) {
  15718. result.parent = newParent;
  15719. }
  15720. if (!doNotCloneChildren) {
  15721. // Children
  15722. var directDescendants = this.getDescendants(true);
  15723. for (var index = 0; index < directDescendants.length; index++) {
  15724. var child = directDescendants[index];
  15725. if (child.clone) {
  15726. child.clone(name + "." + child.name, result);
  15727. }
  15728. }
  15729. }
  15730. return result;
  15731. };
  15732. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15733. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15734. serializationObject.type = this.getClassName();
  15735. // Parent
  15736. if (this.parent) {
  15737. serializationObject.parentId = this.parent.id;
  15738. }
  15739. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15740. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15741. }
  15742. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15743. serializationObject.isEnabled = this.isEnabled();
  15744. // Parent
  15745. if (this.parent) {
  15746. serializationObject.parentId = this.parent.id;
  15747. }
  15748. return serializationObject;
  15749. };
  15750. // Statics
  15751. /**
  15752. * Returns a new TransformNode object parsed from the source provided.
  15753. * The parameter `parsedMesh` is the source.
  15754. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15755. */
  15756. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15757. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15758. if (BABYLON.Tags) {
  15759. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15760. }
  15761. if (parsedTransformNode.localMatrix) {
  15762. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15763. }
  15764. else if (parsedTransformNode.pivotMatrix) {
  15765. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15766. }
  15767. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15768. // Parent
  15769. if (parsedTransformNode.parentId) {
  15770. transformNode._waitingParentId = parsedTransformNode.parentId;
  15771. }
  15772. return transformNode;
  15773. };
  15774. /**
  15775. * Disposes the TransformNode.
  15776. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15777. * Returns nothing.
  15778. */
  15779. TransformNode.prototype.dispose = function (doNotRecurse) {
  15780. // Animations
  15781. this.getScene().stopAnimation(this);
  15782. // Remove from scene
  15783. this.getScene().removeTransformNode(this);
  15784. if (!doNotRecurse) {
  15785. // Children
  15786. var objects = this.getDescendants(true);
  15787. for (var index = 0; index < objects.length; index++) {
  15788. objects[index].dispose();
  15789. }
  15790. }
  15791. else {
  15792. var childMeshes = this.getChildMeshes(true);
  15793. for (index = 0; index < childMeshes.length; index++) {
  15794. var child = childMeshes[index];
  15795. child.parent = null;
  15796. child.computeWorldMatrix(true);
  15797. }
  15798. }
  15799. this.onAfterWorldMatrixUpdateObservable.clear();
  15800. _super.prototype.dispose.call(this);
  15801. };
  15802. // Statics
  15803. TransformNode.BILLBOARDMODE_NONE = 0;
  15804. TransformNode.BILLBOARDMODE_X = 1;
  15805. TransformNode.BILLBOARDMODE_Y = 2;
  15806. TransformNode.BILLBOARDMODE_Z = 4;
  15807. TransformNode.BILLBOARDMODE_ALL = 7;
  15808. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15809. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15810. __decorate([
  15811. BABYLON.serializeAsVector3()
  15812. ], TransformNode.prototype, "_rotation", void 0);
  15813. __decorate([
  15814. BABYLON.serializeAsQuaternion()
  15815. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15816. __decorate([
  15817. BABYLON.serializeAsVector3()
  15818. ], TransformNode.prototype, "_scaling", void 0);
  15819. __decorate([
  15820. BABYLON.serialize()
  15821. ], TransformNode.prototype, "billboardMode", void 0);
  15822. __decorate([
  15823. BABYLON.serialize()
  15824. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15825. __decorate([
  15826. BABYLON.serialize()
  15827. ], TransformNode.prototype, "infiniteDistance", void 0);
  15828. __decorate([
  15829. BABYLON.serializeAsVector3()
  15830. ], TransformNode.prototype, "position", void 0);
  15831. return TransformNode;
  15832. }(BABYLON.Node));
  15833. BABYLON.TransformNode = TransformNode;
  15834. })(BABYLON || (BABYLON = {}));
  15835. //# sourceMappingURL=babylon.transformNode.js.map
  15836. var BABYLON;
  15837. (function (BABYLON) {
  15838. var AbstractMesh = /** @class */ (function (_super) {
  15839. __extends(AbstractMesh, _super);
  15840. // Constructor
  15841. function AbstractMesh(name, scene) {
  15842. if (scene === void 0) { scene = null; }
  15843. var _this = _super.call(this, name, scene, false) || this;
  15844. _this._facetNb = 0; // facet number
  15845. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15846. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15847. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15848. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15849. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15850. _this._subDiv = {
  15851. max: 1,
  15852. X: 1,
  15853. Y: 1,
  15854. Z: 1
  15855. };
  15856. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15857. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15858. // Events
  15859. /**
  15860. * An event triggered when this mesh collides with another one
  15861. * @type {BABYLON.Observable}
  15862. */
  15863. _this.onCollideObservable = new BABYLON.Observable();
  15864. /**
  15865. * An event triggered when the collision's position changes
  15866. * @type {BABYLON.Observable}
  15867. */
  15868. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15869. /**
  15870. * An event triggered when material is changed
  15871. * @type {BABYLON.Observable}
  15872. */
  15873. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15874. // Properties
  15875. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15876. /**
  15877. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15878. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15879. * or
  15880. * 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.
  15881. * for more info check WebGl documentations
  15882. */
  15883. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15884. /**
  15885. * 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:
  15886. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15887. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15888. * 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.
  15889. */
  15890. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15891. /**
  15892. * 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.
  15893. * The default value is -1 which means don't break the query and wait till the result.
  15894. */
  15895. _this.occlusionRetryCount = -1;
  15896. _this._occlusionInternalRetryCounter = 0;
  15897. _this._isOccluded = false;
  15898. _this._isOcclusionQueryInProgress = false;
  15899. _this._visibility = 1.0;
  15900. _this.alphaIndex = Number.MAX_VALUE;
  15901. _this.isVisible = true;
  15902. _this.isPickable = true;
  15903. _this.showBoundingBox = false;
  15904. _this.showSubMeshesBoundingBox = false;
  15905. _this.isBlocker = false;
  15906. _this.enablePointerMoveEvents = false;
  15907. _this.renderingGroupId = 0;
  15908. _this._receiveShadows = false;
  15909. _this.renderOutline = false;
  15910. _this.outlineColor = BABYLON.Color3.Red();
  15911. _this.outlineWidth = 0.02;
  15912. _this.renderOverlay = false;
  15913. _this.overlayColor = BABYLON.Color3.Red();
  15914. _this.overlayAlpha = 0.5;
  15915. _this._hasVertexAlpha = false;
  15916. _this._useVertexColors = true;
  15917. _this._computeBonesUsingShaders = true;
  15918. _this._numBoneInfluencers = 4;
  15919. _this._applyFog = true;
  15920. _this.useOctreeForRenderingSelection = true;
  15921. _this.useOctreeForPicking = true;
  15922. _this.useOctreeForCollisions = true;
  15923. _this._layerMask = 0x0FFFFFFF;
  15924. /**
  15925. * True if the mesh must be rendered in any case.
  15926. */
  15927. _this.alwaysSelectAsActiveMesh = false;
  15928. /**
  15929. * This scene's action manager
  15930. * @type {BABYLON.ActionManager}
  15931. */
  15932. _this.actionManager = null;
  15933. // Physics
  15934. _this.physicsImpostor = null;
  15935. // Collisions
  15936. _this._checkCollisions = false;
  15937. _this._collisionMask = -1;
  15938. _this._collisionGroup = -1;
  15939. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15940. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15941. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15942. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15943. // Edges
  15944. _this.edgesWidth = 1;
  15945. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15946. // Cache
  15947. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15948. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15949. _this._isDisposed = false;
  15950. _this._renderId = 0;
  15951. _this._intersectionsInProgress = new Array();
  15952. _this._unIndexed = false;
  15953. _this._lightSources = new Array();
  15954. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15955. if (collidedMesh === void 0) { collidedMesh = null; }
  15956. //TODO move this to the collision coordinator!
  15957. if (_this.getScene().workerCollisions)
  15958. newPosition.multiplyInPlace(_this._collider._radius);
  15959. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15960. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15961. _this.position.addInPlace(_this._diffPositionForCollisions);
  15962. }
  15963. if (collidedMesh) {
  15964. _this.onCollideObservable.notifyObservers(collidedMesh);
  15965. }
  15966. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15967. };
  15968. _this.getScene().addMesh(_this);
  15969. _this._resyncLightSources();
  15970. return _this;
  15971. }
  15972. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15973. get: function () {
  15974. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15980. get: function () {
  15981. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15982. },
  15983. enumerable: true,
  15984. configurable: true
  15985. });
  15986. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15987. get: function () {
  15988. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15994. get: function () {
  15995. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16001. get: function () {
  16002. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16003. },
  16004. enumerable: true,
  16005. configurable: true
  16006. });
  16007. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16008. /**
  16009. * Read-only : the number of facets in the mesh
  16010. */
  16011. get: function () {
  16012. return this._facetNb;
  16013. },
  16014. enumerable: true,
  16015. configurable: true
  16016. });
  16017. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16018. /**
  16019. * The number (integer) of subdivisions per axis in the partioning space
  16020. */
  16021. get: function () {
  16022. return this._partitioningSubdivisions;
  16023. },
  16024. set: function (nb) {
  16025. this._partitioningSubdivisions = nb;
  16026. },
  16027. enumerable: true,
  16028. configurable: true
  16029. });
  16030. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16031. /**
  16032. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16033. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16034. */
  16035. get: function () {
  16036. return this._partitioningBBoxRatio;
  16037. },
  16038. set: function (ratio) {
  16039. this._partitioningBBoxRatio = ratio;
  16040. },
  16041. enumerable: true,
  16042. configurable: true
  16043. });
  16044. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16045. /**
  16046. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16047. * Works only for updatable meshes.
  16048. * Doesn't work with multi-materials.
  16049. */
  16050. get: function () {
  16051. return this._facetDepthSort;
  16052. },
  16053. set: function (sort) {
  16054. this._facetDepthSort = sort;
  16055. },
  16056. enumerable: true,
  16057. configurable: true
  16058. });
  16059. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16060. /**
  16061. * The location (Vector3) where the facet depth sort must be computed from.
  16062. * By default, the active camera position.
  16063. * Used only when facet depth sort is enabled.
  16064. */
  16065. get: function () {
  16066. return this._facetDepthSortFrom;
  16067. },
  16068. set: function (location) {
  16069. this._facetDepthSortFrom = location;
  16070. },
  16071. enumerable: true,
  16072. configurable: true
  16073. });
  16074. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16075. /**
  16076. * Read-only boolean : is the feature facetData enabled ?
  16077. */
  16078. get: function () {
  16079. return this._facetDataEnabled;
  16080. },
  16081. enumerable: true,
  16082. configurable: true
  16083. });
  16084. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16085. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16086. return false;
  16087. }
  16088. this._markSubMeshesAsMiscDirty();
  16089. return true;
  16090. };
  16091. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16092. set: function (callback) {
  16093. if (this._onCollideObserver) {
  16094. this.onCollideObservable.remove(this._onCollideObserver);
  16095. }
  16096. this._onCollideObserver = this.onCollideObservable.add(callback);
  16097. },
  16098. enumerable: true,
  16099. configurable: true
  16100. });
  16101. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16102. set: function (callback) {
  16103. if (this._onCollisionPositionChangeObserver) {
  16104. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16105. }
  16106. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16107. },
  16108. enumerable: true,
  16109. configurable: true
  16110. });
  16111. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16112. /**
  16113. * 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.
  16114. */
  16115. get: function () {
  16116. return this._isOccluded;
  16117. },
  16118. set: function (value) {
  16119. this._isOccluded = value;
  16120. },
  16121. enumerable: true,
  16122. configurable: true
  16123. });
  16124. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16125. /**
  16126. * Flag to check the progress status of the query
  16127. */
  16128. get: function () {
  16129. return this._isOcclusionQueryInProgress;
  16130. },
  16131. enumerable: true,
  16132. configurable: true
  16133. });
  16134. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16135. /**
  16136. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16137. */
  16138. get: function () {
  16139. return this._visibility;
  16140. },
  16141. /**
  16142. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16143. */
  16144. set: function (value) {
  16145. if (this._visibility === value) {
  16146. return;
  16147. }
  16148. this._visibility = value;
  16149. this._markSubMeshesAsMiscDirty();
  16150. },
  16151. enumerable: true,
  16152. configurable: true
  16153. });
  16154. Object.defineProperty(AbstractMesh.prototype, "material", {
  16155. get: function () {
  16156. return this._material;
  16157. },
  16158. set: function (value) {
  16159. if (this._material === value) {
  16160. return;
  16161. }
  16162. this._material = value;
  16163. if (this.onMaterialChangedObservable.hasObservers) {
  16164. this.onMaterialChangedObservable.notifyObservers(this);
  16165. }
  16166. if (!this.subMeshes) {
  16167. return;
  16168. }
  16169. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16170. var subMesh = _a[_i];
  16171. subMesh.setEffect(null);
  16172. }
  16173. },
  16174. enumerable: true,
  16175. configurable: true
  16176. });
  16177. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16178. get: function () {
  16179. return this._receiveShadows;
  16180. },
  16181. set: function (value) {
  16182. if (this._receiveShadows === value) {
  16183. return;
  16184. }
  16185. this._receiveShadows = value;
  16186. this._markSubMeshesAsLightDirty();
  16187. },
  16188. enumerable: true,
  16189. configurable: true
  16190. });
  16191. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16192. get: function () {
  16193. return this._hasVertexAlpha;
  16194. },
  16195. set: function (value) {
  16196. if (this._hasVertexAlpha === value) {
  16197. return;
  16198. }
  16199. this._hasVertexAlpha = value;
  16200. this._markSubMeshesAsAttributesDirty();
  16201. this._markSubMeshesAsMiscDirty();
  16202. },
  16203. enumerable: true,
  16204. configurable: true
  16205. });
  16206. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16207. get: function () {
  16208. return this._useVertexColors;
  16209. },
  16210. set: function (value) {
  16211. if (this._useVertexColors === value) {
  16212. return;
  16213. }
  16214. this._useVertexColors = value;
  16215. this._markSubMeshesAsAttributesDirty();
  16216. },
  16217. enumerable: true,
  16218. configurable: true
  16219. });
  16220. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16221. get: function () {
  16222. return this._computeBonesUsingShaders;
  16223. },
  16224. set: function (value) {
  16225. if (this._computeBonesUsingShaders === value) {
  16226. return;
  16227. }
  16228. this._computeBonesUsingShaders = value;
  16229. this._markSubMeshesAsAttributesDirty();
  16230. },
  16231. enumerable: true,
  16232. configurable: true
  16233. });
  16234. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16235. get: function () {
  16236. return this._numBoneInfluencers;
  16237. },
  16238. set: function (value) {
  16239. if (this._numBoneInfluencers === value) {
  16240. return;
  16241. }
  16242. this._numBoneInfluencers = value;
  16243. this._markSubMeshesAsAttributesDirty();
  16244. },
  16245. enumerable: true,
  16246. configurable: true
  16247. });
  16248. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16249. get: function () {
  16250. return this._applyFog;
  16251. },
  16252. set: function (value) {
  16253. if (this._applyFog === value) {
  16254. return;
  16255. }
  16256. this._applyFog = value;
  16257. this._markSubMeshesAsMiscDirty();
  16258. },
  16259. enumerable: true,
  16260. configurable: true
  16261. });
  16262. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16263. get: function () {
  16264. return this._layerMask;
  16265. },
  16266. set: function (value) {
  16267. if (value === this._layerMask) {
  16268. return;
  16269. }
  16270. this._layerMask = value;
  16271. this._resyncLightSources();
  16272. },
  16273. enumerable: true,
  16274. configurable: true
  16275. });
  16276. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16277. get: function () {
  16278. return this._collisionMask;
  16279. },
  16280. set: function (mask) {
  16281. this._collisionMask = !isNaN(mask) ? mask : -1;
  16282. },
  16283. enumerable: true,
  16284. configurable: true
  16285. });
  16286. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16287. get: function () {
  16288. return this._collisionGroup;
  16289. },
  16290. set: function (mask) {
  16291. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16292. },
  16293. enumerable: true,
  16294. configurable: true
  16295. });
  16296. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16297. get: function () {
  16298. return null;
  16299. },
  16300. enumerable: true,
  16301. configurable: true
  16302. });
  16303. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16304. get: function () {
  16305. return this._skeleton;
  16306. },
  16307. set: function (value) {
  16308. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16309. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16310. }
  16311. if (value && value.needInitialSkinMatrix) {
  16312. value._registerMeshWithPoseMatrix(this);
  16313. }
  16314. this._skeleton = value;
  16315. if (!this._skeleton) {
  16316. this._bonesTransformMatrices = null;
  16317. }
  16318. this._markSubMeshesAsAttributesDirty();
  16319. },
  16320. enumerable: true,
  16321. configurable: true
  16322. });
  16323. /**
  16324. * Boolean : true if the mesh has been disposed.
  16325. */
  16326. AbstractMesh.prototype.isDisposed = function () {
  16327. return this._isDisposed;
  16328. };
  16329. /**
  16330. * Returns the string "AbstractMesh"
  16331. */
  16332. AbstractMesh.prototype.getClassName = function () {
  16333. return "AbstractMesh";
  16334. };
  16335. /**
  16336. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16337. */
  16338. AbstractMesh.prototype.toString = function (fullDetails) {
  16339. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16340. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16341. if (this._skeleton) {
  16342. ret += ", skeleton: " + this._skeleton.name;
  16343. }
  16344. if (fullDetails) {
  16345. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16346. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16347. }
  16348. return ret;
  16349. };
  16350. AbstractMesh.prototype._rebuild = function () {
  16351. if (this._occlusionQuery) {
  16352. this._occlusionQuery = null;
  16353. }
  16354. if (this._edgesRenderer) {
  16355. this._edgesRenderer._rebuild();
  16356. }
  16357. if (!this.subMeshes) {
  16358. return;
  16359. }
  16360. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16361. var subMesh = _a[_i];
  16362. subMesh._rebuild();
  16363. }
  16364. };
  16365. AbstractMesh.prototype._resyncLightSources = function () {
  16366. this._lightSources.length = 0;
  16367. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16368. var light = _a[_i];
  16369. if (!light.isEnabled()) {
  16370. continue;
  16371. }
  16372. if (light.canAffectMesh(this)) {
  16373. this._lightSources.push(light);
  16374. }
  16375. }
  16376. this._markSubMeshesAsLightDirty();
  16377. };
  16378. AbstractMesh.prototype._resyncLighSource = function (light) {
  16379. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16380. var index = this._lightSources.indexOf(light);
  16381. if (index === -1) {
  16382. if (!isIn) {
  16383. return;
  16384. }
  16385. this._lightSources.push(light);
  16386. }
  16387. else {
  16388. if (isIn) {
  16389. return;
  16390. }
  16391. this._lightSources.splice(index, 1);
  16392. }
  16393. this._markSubMeshesAsLightDirty();
  16394. };
  16395. AbstractMesh.prototype._removeLightSource = function (light) {
  16396. var index = this._lightSources.indexOf(light);
  16397. if (index === -1) {
  16398. return;
  16399. }
  16400. this._lightSources.splice(index, 1);
  16401. this._markSubMeshesAsLightDirty();
  16402. };
  16403. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16404. if (!this.subMeshes) {
  16405. return;
  16406. }
  16407. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16408. var subMesh = _a[_i];
  16409. if (subMesh._materialDefines) {
  16410. func(subMesh._materialDefines);
  16411. }
  16412. }
  16413. };
  16414. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16415. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16416. };
  16417. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16418. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16419. };
  16420. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16421. if (!this.subMeshes) {
  16422. return;
  16423. }
  16424. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16425. var subMesh = _a[_i];
  16426. var material = subMesh.getMaterial();
  16427. if (material) {
  16428. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16429. }
  16430. }
  16431. };
  16432. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16433. /**
  16434. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16435. * Default : (1.0, 1.0, 1.0)
  16436. */
  16437. get: function () {
  16438. return this._scaling;
  16439. },
  16440. /**
  16441. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16442. * Default : (1.0, 1.0, 1.0)
  16443. */
  16444. set: function (newScaling) {
  16445. this._scaling = newScaling;
  16446. if (this.physicsImpostor) {
  16447. this.physicsImpostor.forceUpdate();
  16448. }
  16449. },
  16450. enumerable: true,
  16451. configurable: true
  16452. });
  16453. // Methods
  16454. /**
  16455. * Disables the mesh edger rendering mode.
  16456. * Returns the AbstractMesh.
  16457. */
  16458. AbstractMesh.prototype.disableEdgesRendering = function () {
  16459. if (this._edgesRenderer) {
  16460. this._edgesRenderer.dispose();
  16461. this._edgesRenderer = null;
  16462. }
  16463. return this;
  16464. };
  16465. /**
  16466. * Enables the edge rendering mode on the mesh.
  16467. * This mode makes the mesh edges visible.
  16468. * Returns the AbstractMesh.
  16469. */
  16470. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16471. if (epsilon === void 0) { epsilon = 0.95; }
  16472. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16473. this.disableEdgesRendering();
  16474. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16475. return this;
  16476. };
  16477. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16478. /**
  16479. * Returns true if the mesh is blocked. Used by the class Mesh.
  16480. * Returns the boolean `false` by default.
  16481. */
  16482. get: function () {
  16483. return false;
  16484. },
  16485. enumerable: true,
  16486. configurable: true
  16487. });
  16488. /**
  16489. * Returns the mesh itself by default, used by the class Mesh.
  16490. * Returned type : AbstractMesh
  16491. */
  16492. AbstractMesh.prototype.getLOD = function (camera) {
  16493. return this;
  16494. };
  16495. /**
  16496. * Returns 0 by default, used by the class Mesh.
  16497. * Returns an integer.
  16498. */
  16499. AbstractMesh.prototype.getTotalVertices = function () {
  16500. return 0;
  16501. };
  16502. /**
  16503. * Returns null by default, used by the class Mesh.
  16504. * Returned type : integer array
  16505. */
  16506. AbstractMesh.prototype.getIndices = function () {
  16507. return null;
  16508. };
  16509. /**
  16510. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16511. * Returned type : float array or Float32Array
  16512. */
  16513. AbstractMesh.prototype.getVerticesData = function (kind) {
  16514. return null;
  16515. };
  16516. /**
  16517. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16518. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16519. * The `data` are either a numeric array either a Float32Array.
  16520. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16521. * 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).
  16522. * Note that a new underlying VertexBuffer object is created each call.
  16523. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16524. *
  16525. * Possible `kind` values :
  16526. * - BABYLON.VertexBuffer.PositionKind
  16527. * - BABYLON.VertexBuffer.UVKind
  16528. * - BABYLON.VertexBuffer.UV2Kind
  16529. * - BABYLON.VertexBuffer.UV3Kind
  16530. * - BABYLON.VertexBuffer.UV4Kind
  16531. * - BABYLON.VertexBuffer.UV5Kind
  16532. * - BABYLON.VertexBuffer.UV6Kind
  16533. * - BABYLON.VertexBuffer.ColorKind
  16534. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16535. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16536. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16537. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16538. *
  16539. * Returns the Mesh.
  16540. */
  16541. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16542. return this;
  16543. };
  16544. /**
  16545. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16546. * If the mesh has no geometry, it is simply returned as it is.
  16547. * The `data` are either a numeric array either a Float32Array.
  16548. * No new underlying VertexBuffer object is created.
  16549. * 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.
  16550. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16551. *
  16552. * Possible `kind` values :
  16553. * - BABYLON.VertexBuffer.PositionKind
  16554. * - BABYLON.VertexBuffer.UVKind
  16555. * - BABYLON.VertexBuffer.UV2Kind
  16556. * - BABYLON.VertexBuffer.UV3Kind
  16557. * - BABYLON.VertexBuffer.UV4Kind
  16558. * - BABYLON.VertexBuffer.UV5Kind
  16559. * - BABYLON.VertexBuffer.UV6Kind
  16560. * - BABYLON.VertexBuffer.ColorKind
  16561. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16562. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16563. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16564. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16565. *
  16566. * Returns the Mesh.
  16567. */
  16568. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16569. return this;
  16570. };
  16571. /**
  16572. * Sets the mesh indices.
  16573. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16574. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16575. * This method creates a new index buffer each call.
  16576. * Returns the Mesh.
  16577. */
  16578. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16579. return this;
  16580. };
  16581. /** Returns false by default, used by the class Mesh.
  16582. * Returns a boolean
  16583. */
  16584. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16585. return false;
  16586. };
  16587. /**
  16588. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16589. * Returns a BoundingInfo
  16590. */
  16591. AbstractMesh.prototype.getBoundingInfo = function () {
  16592. if (this._masterMesh) {
  16593. return this._masterMesh.getBoundingInfo();
  16594. }
  16595. if (!this._boundingInfo) {
  16596. // this._boundingInfo is being created here
  16597. this._updateBoundingInfo();
  16598. }
  16599. // cannot be null.
  16600. return this._boundingInfo;
  16601. };
  16602. /**
  16603. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16604. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16605. */
  16606. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16607. if (includeDescendants === void 0) { includeDescendants = true; }
  16608. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16609. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16610. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16611. if (maxDimension === 0) {
  16612. return this;
  16613. }
  16614. var scale = 1 / maxDimension;
  16615. this.scaling.scaleInPlace(scale);
  16616. return this;
  16617. };
  16618. /**
  16619. * Sets a mesh new object BoundingInfo.
  16620. * Returns the AbstractMesh.
  16621. */
  16622. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16623. this._boundingInfo = boundingInfo;
  16624. return this;
  16625. };
  16626. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16627. get: function () {
  16628. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16629. },
  16630. enumerable: true,
  16631. configurable: true
  16632. });
  16633. AbstractMesh.prototype._preActivate = function () {
  16634. };
  16635. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16636. };
  16637. AbstractMesh.prototype._activate = function (renderId) {
  16638. this._renderId = renderId;
  16639. };
  16640. /**
  16641. * Returns the latest update of the World matrix
  16642. * Returns a Matrix.
  16643. */
  16644. AbstractMesh.prototype.getWorldMatrix = function () {
  16645. if (this._masterMesh) {
  16646. return this._masterMesh.getWorldMatrix();
  16647. }
  16648. return _super.prototype.getWorldMatrix.call(this);
  16649. };
  16650. /**
  16651. * Returns the latest update of the World matrix determinant.
  16652. */
  16653. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16654. if (this._masterMesh) {
  16655. return this._masterMesh._getWorldMatrixDeterminant();
  16656. }
  16657. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16658. };
  16659. // ================================== Point of View Movement =================================
  16660. /**
  16661. * Perform relative position change from the point of view of behind the front of the mesh.
  16662. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16663. * Supports definition of mesh facing forward or backward.
  16664. * @param {number} amountRight
  16665. * @param {number} amountUp
  16666. * @param {number} amountForward
  16667. *
  16668. * Returns the AbstractMesh.
  16669. */
  16670. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16671. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16672. return this;
  16673. };
  16674. /**
  16675. * Calculate relative position change from the point of view of behind the front of the mesh.
  16676. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16677. * Supports definition of mesh facing forward or backward.
  16678. * @param {number} amountRight
  16679. * @param {number} amountUp
  16680. * @param {number} amountForward
  16681. *
  16682. * Returns a new Vector3.
  16683. */
  16684. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16685. var rotMatrix = new BABYLON.Matrix();
  16686. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16687. rotQuaternion.toRotationMatrix(rotMatrix);
  16688. var translationDelta = BABYLON.Vector3.Zero();
  16689. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16690. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16691. return translationDelta;
  16692. };
  16693. // ================================== Point of View Rotation =================================
  16694. /**
  16695. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16696. * Supports definition of mesh facing forward or backward.
  16697. * @param {number} flipBack
  16698. * @param {number} twirlClockwise
  16699. * @param {number} tiltRight
  16700. *
  16701. * Returns the AbstractMesh.
  16702. */
  16703. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16704. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16705. return this;
  16706. };
  16707. /**
  16708. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16709. * Supports definition of mesh facing forward or backward.
  16710. * @param {number} flipBack
  16711. * @param {number} twirlClockwise
  16712. * @param {number} tiltRight
  16713. *
  16714. * Returns a new Vector3.
  16715. */
  16716. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16717. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16718. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16719. };
  16720. /**
  16721. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16722. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16723. */
  16724. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16725. if (includeDescendants === void 0) { includeDescendants = true; }
  16726. this.computeWorldMatrix(true);
  16727. var min;
  16728. var max;
  16729. var boundingInfo = this.getBoundingInfo();
  16730. if (!this.subMeshes) {
  16731. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16732. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16733. }
  16734. else {
  16735. min = boundingInfo.boundingBox.minimumWorld;
  16736. max = boundingInfo.boundingBox.maximumWorld;
  16737. }
  16738. if (includeDescendants) {
  16739. var descendants = this.getDescendants(false);
  16740. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16741. var descendant = descendants_1[_i];
  16742. var childMesh = descendant;
  16743. childMesh.computeWorldMatrix(true);
  16744. //make sure we have the needed params to get mix and max
  16745. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16746. continue;
  16747. }
  16748. var childBoundingInfo = childMesh.getBoundingInfo();
  16749. var boundingBox = childBoundingInfo.boundingBox;
  16750. var minBox = boundingBox.minimumWorld;
  16751. var maxBox = boundingBox.maximumWorld;
  16752. BABYLON.Tools.CheckExtends(minBox, min, max);
  16753. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16754. }
  16755. }
  16756. return {
  16757. min: min,
  16758. max: max
  16759. };
  16760. };
  16761. /**
  16762. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16763. * Returns the AbstractMesh.
  16764. */
  16765. AbstractMesh.prototype._updateBoundingInfo = function () {
  16766. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16767. this._boundingInfo.update(this.worldMatrixFromCache);
  16768. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16769. return this;
  16770. };
  16771. /**
  16772. * Update a mesh's children BoundingInfo objects only.
  16773. * Returns the AbstractMesh.
  16774. */
  16775. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16776. if (!this.subMeshes) {
  16777. return this;
  16778. }
  16779. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16780. var subMesh = this.subMeshes[subIndex];
  16781. if (!subMesh.IsGlobal) {
  16782. subMesh.updateBoundingInfo(matrix);
  16783. }
  16784. }
  16785. return this;
  16786. };
  16787. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16788. // Bounding info
  16789. this._updateBoundingInfo();
  16790. };
  16791. /**
  16792. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16793. * A mesh is in the frustum if its bounding box intersects the frustum.
  16794. * Boolean returned.
  16795. */
  16796. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16797. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16798. };
  16799. /**
  16800. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16801. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16802. * Boolean returned.
  16803. */
  16804. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16805. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16806. ;
  16807. };
  16808. /**
  16809. * True if the mesh intersects another mesh or a SolidParticle object.
  16810. * 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)
  16811. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16812. * Returns a boolean.
  16813. */
  16814. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16815. if (precise === void 0) { precise = false; }
  16816. if (!this._boundingInfo || !mesh._boundingInfo) {
  16817. return false;
  16818. }
  16819. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16820. return true;
  16821. }
  16822. if (includeDescendants) {
  16823. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16824. var child = _a[_i];
  16825. if (child.intersectsMesh(mesh, precise, true)) {
  16826. return true;
  16827. }
  16828. }
  16829. }
  16830. return false;
  16831. };
  16832. /**
  16833. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16834. * Returns a boolean.
  16835. */
  16836. AbstractMesh.prototype.intersectsPoint = function (point) {
  16837. if (!this._boundingInfo) {
  16838. return false;
  16839. }
  16840. return this._boundingInfo.intersectsPoint(point);
  16841. };
  16842. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16843. return this.physicsImpostor;
  16844. };
  16845. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16846. if (camera === void 0) { camera = null; }
  16847. if (!camera) {
  16848. camera = this.getScene().activeCamera;
  16849. }
  16850. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16851. };
  16852. /**
  16853. * Returns the distance from the mesh to the active camera.
  16854. * Returns a float.
  16855. */
  16856. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16857. if (camera === void 0) { camera = null; }
  16858. if (!camera) {
  16859. camera = this.getScene().activeCamera;
  16860. }
  16861. return this.absolutePosition.subtract(camera.position).length();
  16862. };
  16863. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16864. if (!this.physicsImpostor) {
  16865. return this;
  16866. }
  16867. this.physicsImpostor.applyImpulse(force, contactPoint);
  16868. return this;
  16869. };
  16870. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16871. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16872. return this;
  16873. }
  16874. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16875. mainPivot: pivot1,
  16876. connectedPivot: pivot2,
  16877. nativeParams: options
  16878. });
  16879. return this;
  16880. };
  16881. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16882. // Collisions
  16883. /**
  16884. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16885. * Default `false`.
  16886. */
  16887. get: function () {
  16888. return this._checkCollisions;
  16889. },
  16890. set: function (collisionEnabled) {
  16891. this._checkCollisions = collisionEnabled;
  16892. if (this.getScene().workerCollisions) {
  16893. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16894. }
  16895. },
  16896. enumerable: true,
  16897. configurable: true
  16898. });
  16899. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16900. /**
  16901. * Gets Collider object used to compute collisions (not physics)
  16902. */
  16903. get: function () {
  16904. return this._collider;
  16905. },
  16906. enumerable: true,
  16907. configurable: true
  16908. });
  16909. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16910. var globalPosition = this.getAbsolutePosition();
  16911. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16912. if (!this._collider) {
  16913. this._collider = new BABYLON.Collider();
  16914. }
  16915. this._collider._radius = this.ellipsoid;
  16916. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16917. return this;
  16918. };
  16919. // Submeshes octree
  16920. /**
  16921. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16922. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16923. * Returns an Octree of submeshes.
  16924. */
  16925. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16926. if (maxCapacity === void 0) { maxCapacity = 64; }
  16927. if (maxDepth === void 0) { maxDepth = 2; }
  16928. if (!this._submeshesOctree) {
  16929. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16930. }
  16931. this.computeWorldMatrix(true);
  16932. var boundingInfo = this.getBoundingInfo();
  16933. // Update octree
  16934. var bbox = boundingInfo.boundingBox;
  16935. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16936. return this._submeshesOctree;
  16937. };
  16938. // Collisions
  16939. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16940. this._generatePointsArray();
  16941. if (!this._positions) {
  16942. return this;
  16943. }
  16944. // Transformation
  16945. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16946. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16947. subMesh._lastColliderWorldVertices = [];
  16948. subMesh._trianglePlanes = [];
  16949. var start = subMesh.verticesStart;
  16950. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16951. for (var i = start; i < end; i++) {
  16952. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16953. }
  16954. }
  16955. // Collide
  16956. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16957. if (collider.collisionFound) {
  16958. collider.collidedMesh = this;
  16959. }
  16960. return this;
  16961. };
  16962. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16963. var subMeshes;
  16964. var len;
  16965. // Octrees
  16966. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16967. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16968. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16969. len = intersections.length;
  16970. subMeshes = intersections.data;
  16971. }
  16972. else {
  16973. subMeshes = this.subMeshes;
  16974. len = subMeshes.length;
  16975. }
  16976. for (var index = 0; index < len; index++) {
  16977. var subMesh = subMeshes[index];
  16978. // Bounding test
  16979. if (len > 1 && !subMesh._checkCollision(collider))
  16980. continue;
  16981. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16982. }
  16983. return this;
  16984. };
  16985. AbstractMesh.prototype._checkCollision = function (collider) {
  16986. // Bounding box test
  16987. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16988. return this;
  16989. // Transformation matrix
  16990. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16991. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16992. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16993. return this;
  16994. };
  16995. // Picking
  16996. AbstractMesh.prototype._generatePointsArray = function () {
  16997. return false;
  16998. };
  16999. /**
  17000. * Checks if the passed Ray intersects with the mesh.
  17001. * Returns an object PickingInfo.
  17002. */
  17003. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17004. var pickingInfo = new BABYLON.PickingInfo();
  17005. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17006. return pickingInfo;
  17007. }
  17008. if (!this._generatePointsArray()) {
  17009. return pickingInfo;
  17010. }
  17011. var intersectInfo = null;
  17012. // Octrees
  17013. var subMeshes;
  17014. var len;
  17015. if (this._submeshesOctree && this.useOctreeForPicking) {
  17016. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17017. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17018. len = intersections.length;
  17019. subMeshes = intersections.data;
  17020. }
  17021. else {
  17022. subMeshes = this.subMeshes;
  17023. len = subMeshes.length;
  17024. }
  17025. for (var index = 0; index < len; index++) {
  17026. var subMesh = subMeshes[index];
  17027. // Bounding test
  17028. if (len > 1 && !subMesh.canIntersects(ray))
  17029. continue;
  17030. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17031. if (currentIntersectInfo) {
  17032. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17033. intersectInfo = currentIntersectInfo;
  17034. intersectInfo.subMeshId = index;
  17035. if (fastCheck) {
  17036. break;
  17037. }
  17038. }
  17039. }
  17040. }
  17041. if (intersectInfo) {
  17042. // Get picked point
  17043. var world = this.getWorldMatrix();
  17044. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17045. var direction = ray.direction.clone();
  17046. direction = direction.scale(intersectInfo.distance);
  17047. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17048. var pickedPoint = worldOrigin.add(worldDirection);
  17049. // Return result
  17050. pickingInfo.hit = true;
  17051. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17052. pickingInfo.pickedPoint = pickedPoint;
  17053. pickingInfo.pickedMesh = this;
  17054. pickingInfo.bu = intersectInfo.bu || 0;
  17055. pickingInfo.bv = intersectInfo.bv || 0;
  17056. pickingInfo.faceId = intersectInfo.faceId;
  17057. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17058. return pickingInfo;
  17059. }
  17060. return pickingInfo;
  17061. };
  17062. /**
  17063. * Clones the mesh, used by the class Mesh.
  17064. * Just returns `null` for an AbstractMesh.
  17065. */
  17066. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17067. return null;
  17068. };
  17069. /**
  17070. * Disposes all the mesh submeshes.
  17071. * Returns the AbstractMesh.
  17072. */
  17073. AbstractMesh.prototype.releaseSubMeshes = function () {
  17074. if (this.subMeshes) {
  17075. while (this.subMeshes.length) {
  17076. this.subMeshes[0].dispose();
  17077. }
  17078. }
  17079. else {
  17080. this.subMeshes = new Array();
  17081. }
  17082. return this;
  17083. };
  17084. /**
  17085. * Disposes the AbstractMesh.
  17086. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17087. * Returns nothing.
  17088. */
  17089. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17090. var _this = this;
  17091. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17092. var index;
  17093. // Action manager
  17094. if (this.actionManager !== undefined && this.actionManager !== null) {
  17095. this.actionManager.dispose();
  17096. this.actionManager = null;
  17097. }
  17098. // Skeleton
  17099. this.skeleton = null;
  17100. // Physics
  17101. if (this.physicsImpostor) {
  17102. this.physicsImpostor.dispose();
  17103. }
  17104. // Intersections in progress
  17105. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17106. var other = this._intersectionsInProgress[index];
  17107. var pos = other._intersectionsInProgress.indexOf(this);
  17108. other._intersectionsInProgress.splice(pos, 1);
  17109. }
  17110. this._intersectionsInProgress = [];
  17111. // Lights
  17112. var lights = this.getScene().lights;
  17113. lights.forEach(function (light) {
  17114. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17115. if (meshIndex !== -1) {
  17116. light.includedOnlyMeshes.splice(meshIndex, 1);
  17117. }
  17118. meshIndex = light.excludedMeshes.indexOf(_this);
  17119. if (meshIndex !== -1) {
  17120. light.excludedMeshes.splice(meshIndex, 1);
  17121. }
  17122. // Shadow generators
  17123. var generator = light.getShadowGenerator();
  17124. if (generator) {
  17125. var shadowMap = generator.getShadowMap();
  17126. if (shadowMap && shadowMap.renderList) {
  17127. meshIndex = shadowMap.renderList.indexOf(_this);
  17128. if (meshIndex !== -1) {
  17129. shadowMap.renderList.splice(meshIndex, 1);
  17130. }
  17131. }
  17132. }
  17133. });
  17134. // Edges
  17135. if (this._edgesRenderer) {
  17136. this._edgesRenderer.dispose();
  17137. this._edgesRenderer = null;
  17138. }
  17139. // SubMeshes
  17140. if (this.getClassName() !== "InstancedMesh") {
  17141. this.releaseSubMeshes();
  17142. }
  17143. // Octree
  17144. var sceneOctree = this.getScene().selectionOctree;
  17145. if (sceneOctree !== undefined && sceneOctree !== null) {
  17146. var index = sceneOctree.dynamicContent.indexOf(this);
  17147. if (index !== -1) {
  17148. sceneOctree.dynamicContent.splice(index, 1);
  17149. }
  17150. }
  17151. // Query
  17152. var engine = this.getScene().getEngine();
  17153. if (this._occlusionQuery) {
  17154. this._isOcclusionQueryInProgress = false;
  17155. engine.deleteQuery(this._occlusionQuery);
  17156. this._occlusionQuery = null;
  17157. }
  17158. // Engine
  17159. engine.wipeCaches();
  17160. // Remove from scene
  17161. this.getScene().removeMesh(this);
  17162. if (disposeMaterialAndTextures) {
  17163. if (this.material) {
  17164. this.material.dispose(false, true);
  17165. }
  17166. }
  17167. if (!doNotRecurse) {
  17168. // Particles
  17169. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17170. if (this.getScene().particleSystems[index].emitter === this) {
  17171. this.getScene().particleSystems[index].dispose();
  17172. index--;
  17173. }
  17174. }
  17175. }
  17176. // facet data
  17177. if (this._facetDataEnabled) {
  17178. this.disableFacetData();
  17179. }
  17180. this.onAfterWorldMatrixUpdateObservable.clear();
  17181. this.onCollideObservable.clear();
  17182. this.onCollisionPositionChangeObservable.clear();
  17183. this._isDisposed = true;
  17184. _super.prototype.dispose.call(this, doNotRecurse);
  17185. };
  17186. /**
  17187. * Adds the passed mesh as a child to the current mesh.
  17188. * Returns the AbstractMesh.
  17189. */
  17190. AbstractMesh.prototype.addChild = function (mesh) {
  17191. mesh.setParent(this);
  17192. return this;
  17193. };
  17194. /**
  17195. * Removes the passed mesh from the current mesh children list.
  17196. * Returns the AbstractMesh.
  17197. */
  17198. AbstractMesh.prototype.removeChild = function (mesh) {
  17199. mesh.setParent(null);
  17200. return this;
  17201. };
  17202. // Facet data
  17203. /**
  17204. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17205. * Returns the AbstractMesh.
  17206. */
  17207. AbstractMesh.prototype._initFacetData = function () {
  17208. if (!this._facetNormals) {
  17209. this._facetNormals = new Array();
  17210. }
  17211. if (!this._facetPositions) {
  17212. this._facetPositions = new Array();
  17213. }
  17214. if (!this._facetPartitioning) {
  17215. this._facetPartitioning = new Array();
  17216. }
  17217. this._facetNb = (this.getIndices().length / 3) | 0;
  17218. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17219. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17220. for (var f = 0; f < this._facetNb; f++) {
  17221. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17222. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17223. }
  17224. this._facetDataEnabled = true;
  17225. return this;
  17226. };
  17227. /**
  17228. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17229. * This method can be called within the render loop.
  17230. * 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.
  17231. * Returns the AbstractMesh.
  17232. */
  17233. AbstractMesh.prototype.updateFacetData = function () {
  17234. if (!this._facetDataEnabled) {
  17235. this._initFacetData();
  17236. }
  17237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17238. var indices = this.getIndices();
  17239. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17240. var bInfo = this.getBoundingInfo();
  17241. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17242. // init arrays, matrix and sort function on first call
  17243. this._facetDepthSortEnabled = true;
  17244. if (indices instanceof Uint16Array) {
  17245. this._depthSortedIndices = new Uint16Array(indices);
  17246. }
  17247. else if (indices instanceof Uint32Array) {
  17248. this._depthSortedIndices = new Uint32Array(indices);
  17249. }
  17250. else {
  17251. var needs32bits = false;
  17252. for (var i = 0; i < indices.length; i++) {
  17253. if (indices[i] > 65535) {
  17254. needs32bits = true;
  17255. break;
  17256. }
  17257. }
  17258. if (needs32bits) {
  17259. this._depthSortedIndices = new Uint32Array(indices);
  17260. }
  17261. else {
  17262. this._depthSortedIndices = new Uint16Array(indices);
  17263. }
  17264. }
  17265. this._facetDepthSortFunction = function (f1, f2) {
  17266. return (f2.sqDistance - f1.sqDistance);
  17267. };
  17268. if (!this._facetDepthSortFrom) {
  17269. var camera = this.getScene().activeCamera;
  17270. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17271. }
  17272. this._depthSortedFacets = [];
  17273. for (var f = 0; f < this._facetNb; f++) {
  17274. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17275. this._depthSortedFacets.push(depthSortedFacet);
  17276. }
  17277. this._invertedMatrix = BABYLON.Matrix.Identity();
  17278. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17279. }
  17280. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17281. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17282. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17283. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17284. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17285. this._subDiv.max = this._partitioningSubdivisions;
  17286. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17287. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17288. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17289. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17290. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17291. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17292. // set the parameters for ComputeNormals()
  17293. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17294. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17295. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17296. this._facetParameters.bInfo = bInfo;
  17297. this._facetParameters.bbSize = this._bbSize;
  17298. this._facetParameters.subDiv = this._subDiv;
  17299. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17300. this._facetParameters.depthSort = this._facetDepthSort;
  17301. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17302. this.computeWorldMatrix(true);
  17303. this._worldMatrix.invertToRef(this._invertedMatrix);
  17304. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17305. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17306. }
  17307. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17308. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17309. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17310. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17311. var l = (this._depthSortedIndices.length / 3) | 0;
  17312. for (var f = 0; f < l; f++) {
  17313. var sind = this._depthSortedFacets[f].ind;
  17314. this._depthSortedIndices[f * 3] = indices[sind];
  17315. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17316. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17317. }
  17318. this.updateIndices(this._depthSortedIndices);
  17319. }
  17320. return this;
  17321. };
  17322. /**
  17323. * Returns the facetLocalNormals array.
  17324. * The normals are expressed in the mesh local space.
  17325. */
  17326. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17327. if (!this._facetNormals) {
  17328. this.updateFacetData();
  17329. }
  17330. return this._facetNormals;
  17331. };
  17332. /**
  17333. * Returns the facetLocalPositions array.
  17334. * The facet positions are expressed in the mesh local space.
  17335. */
  17336. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17337. if (!this._facetPositions) {
  17338. this.updateFacetData();
  17339. }
  17340. return this._facetPositions;
  17341. };
  17342. /**
  17343. * Returns the facetLocalPartioning array.
  17344. */
  17345. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17346. if (!this._facetPartitioning) {
  17347. this.updateFacetData();
  17348. }
  17349. return this._facetPartitioning;
  17350. };
  17351. /**
  17352. * Returns the i-th facet position in the world system.
  17353. * This method allocates a new Vector3 per call.
  17354. */
  17355. AbstractMesh.prototype.getFacetPosition = function (i) {
  17356. var pos = BABYLON.Vector3.Zero();
  17357. this.getFacetPositionToRef(i, pos);
  17358. return pos;
  17359. };
  17360. /**
  17361. * Sets the reference Vector3 with the i-th facet position in the world system.
  17362. * Returns the AbstractMesh.
  17363. */
  17364. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17365. var localPos = (this.getFacetLocalPositions())[i];
  17366. var world = this.getWorldMatrix();
  17367. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17368. return this;
  17369. };
  17370. /**
  17371. * Returns the i-th facet normal in the world system.
  17372. * This method allocates a new Vector3 per call.
  17373. */
  17374. AbstractMesh.prototype.getFacetNormal = function (i) {
  17375. var norm = BABYLON.Vector3.Zero();
  17376. this.getFacetNormalToRef(i, norm);
  17377. return norm;
  17378. };
  17379. /**
  17380. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17381. * Returns the AbstractMesh.
  17382. */
  17383. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17384. var localNorm = (this.getFacetLocalNormals())[i];
  17385. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17386. return this;
  17387. };
  17388. /**
  17389. * 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).
  17390. */
  17391. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17392. var bInfo = this.getBoundingInfo();
  17393. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17394. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17395. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17396. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17397. return null;
  17398. }
  17399. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17400. };
  17401. /**
  17402. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17403. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17404. * 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.
  17405. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17406. * 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.
  17407. */
  17408. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17409. if (checkFace === void 0) { checkFace = false; }
  17410. if (facing === void 0) { facing = true; }
  17411. var world = this.getWorldMatrix();
  17412. var invMat = BABYLON.Tmp.Matrix[5];
  17413. world.invertToRef(invMat);
  17414. var invVect = BABYLON.Tmp.Vector3[8];
  17415. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17416. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17417. if (projected) {
  17418. // tranform the local computed projected vector to world coordinates
  17419. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17420. }
  17421. return closest;
  17422. };
  17423. /**
  17424. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17425. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17426. * 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.
  17427. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17428. * 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.
  17429. */
  17430. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17431. if (checkFace === void 0) { checkFace = false; }
  17432. if (facing === void 0) { facing = true; }
  17433. var closest = null;
  17434. var tmpx = 0.0;
  17435. var tmpy = 0.0;
  17436. var tmpz = 0.0;
  17437. var d = 0.0; // tmp dot facet normal * facet position
  17438. var t0 = 0.0;
  17439. var projx = 0.0;
  17440. var projy = 0.0;
  17441. var projz = 0.0;
  17442. // Get all the facets in the same partitioning block than (x, y, z)
  17443. var facetPositions = this.getFacetLocalPositions();
  17444. var facetNormals = this.getFacetLocalNormals();
  17445. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17446. if (!facetsInBlock) {
  17447. return null;
  17448. }
  17449. // Get the closest facet to (x, y, z)
  17450. var shortest = Number.MAX_VALUE; // init distance vars
  17451. var tmpDistance = shortest;
  17452. var fib; // current facet in the block
  17453. var norm; // current facet normal
  17454. var p0; // current facet barycenter position
  17455. // loop on all the facets in the current partitioning block
  17456. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17457. fib = facetsInBlock[idx];
  17458. norm = facetNormals[fib];
  17459. p0 = facetPositions[fib];
  17460. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17461. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17462. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17463. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17464. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17465. projx = x + norm.x * t0;
  17466. projy = y + norm.y * t0;
  17467. projz = z + norm.z * t0;
  17468. tmpx = projx - x;
  17469. tmpy = projy - y;
  17470. tmpz = projz - z;
  17471. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17472. if (tmpDistance < shortest) {
  17473. shortest = tmpDistance;
  17474. closest = fib;
  17475. if (projected) {
  17476. projected.x = projx;
  17477. projected.y = projy;
  17478. projected.z = projz;
  17479. }
  17480. }
  17481. }
  17482. }
  17483. return closest;
  17484. };
  17485. /**
  17486. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17487. */
  17488. AbstractMesh.prototype.getFacetDataParameters = function () {
  17489. return this._facetParameters;
  17490. };
  17491. /**
  17492. * Disables the feature FacetData and frees the related memory.
  17493. * Returns the AbstractMesh.
  17494. */
  17495. AbstractMesh.prototype.disableFacetData = function () {
  17496. if (this._facetDataEnabled) {
  17497. this._facetDataEnabled = false;
  17498. this._facetPositions = new Array();
  17499. this._facetNormals = new Array();
  17500. this._facetPartitioning = new Array();
  17501. this._facetParameters = null;
  17502. this._depthSortedIndices = new Uint32Array(0);
  17503. }
  17504. return this;
  17505. };
  17506. /**
  17507. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17508. * Returns the mesh.
  17509. */
  17510. AbstractMesh.prototype.updateIndices = function (indices) {
  17511. return this;
  17512. };
  17513. /**
  17514. * The mesh Geometry. Actually used by the Mesh object.
  17515. * Returns a blank geometry object.
  17516. */
  17517. /**
  17518. * Creates new normals data for the mesh.
  17519. * @param updatable.
  17520. */
  17521. AbstractMesh.prototype.createNormals = function (updatable) {
  17522. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17523. var indices = this.getIndices();
  17524. var normals;
  17525. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17526. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17527. }
  17528. else {
  17529. normals = [];
  17530. }
  17531. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17532. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17533. };
  17534. /**
  17535. * Align the mesh with a normal.
  17536. * Returns the mesh.
  17537. */
  17538. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17539. if (!upDirection) {
  17540. upDirection = BABYLON.Axis.Y;
  17541. }
  17542. var axisX = BABYLON.Tmp.Vector3[0];
  17543. var axisZ = BABYLON.Tmp.Vector3[1];
  17544. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17545. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17546. if (this.rotationQuaternion) {
  17547. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17548. }
  17549. else {
  17550. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17551. }
  17552. return this;
  17553. };
  17554. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17555. var engine = this.getEngine();
  17556. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17557. this._isOccluded = false;
  17558. return;
  17559. }
  17560. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17561. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17562. if (isOcclusionQueryAvailable) {
  17563. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17564. this._isOcclusionQueryInProgress = false;
  17565. this._occlusionInternalRetryCounter = 0;
  17566. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17567. }
  17568. else {
  17569. this._occlusionInternalRetryCounter++;
  17570. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17571. this._isOcclusionQueryInProgress = false;
  17572. this._occlusionInternalRetryCounter = 0;
  17573. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17574. // if strict continue the last state of the object.
  17575. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17576. }
  17577. else {
  17578. return;
  17579. }
  17580. }
  17581. }
  17582. var scene = this.getScene();
  17583. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17584. if (!this._occlusionQuery) {
  17585. this._occlusionQuery = engine.createQuery();
  17586. }
  17587. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17588. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17589. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17590. this._isOcclusionQueryInProgress = true;
  17591. };
  17592. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17593. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17594. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17595. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17596. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17597. return AbstractMesh;
  17598. }(BABYLON.TransformNode));
  17599. BABYLON.AbstractMesh = AbstractMesh;
  17600. })(BABYLON || (BABYLON = {}));
  17601. //# sourceMappingURL=babylon.abstractMesh.js.map
  17602. var BABYLON;
  17603. (function (BABYLON) {
  17604. /**
  17605. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  17606. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  17607. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  17608. */
  17609. var Light = /** @class */ (function (_super) {
  17610. __extends(Light, _super);
  17611. /**
  17612. * Creates a Light object in the scene.
  17613. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17614. * @param name The firendly name of the light
  17615. * @param scene The scene the light belongs too
  17616. */
  17617. function Light(name, scene) {
  17618. var _this = _super.call(this, name, scene) || this;
  17619. /**
  17620. * Diffuse gives the basic color to an object.
  17621. */
  17622. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17623. /**
  17624. * Specular produces a highlight color on an object.
  17625. * Note: This is note affecting PBR materials.
  17626. */
  17627. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17628. /**
  17629. * Strength of the light.
  17630. * Note: By default it is define in the framework own unit.
  17631. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  17632. */
  17633. _this.intensity = 1.0;
  17634. /**
  17635. * Defines how far from the source the light is impacting in scene units.
  17636. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  17637. */
  17638. _this.range = Number.MAX_VALUE;
  17639. /**
  17640. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17641. * of light.
  17642. */
  17643. _this._photometricScale = 1.0;
  17644. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17645. _this._radius = 0.00001;
  17646. /**
  17647. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  17648. * exceeding the number allowed of the materials.
  17649. */
  17650. _this.renderPriority = 0;
  17651. /**
  17652. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17653. * the current shadow generator.
  17654. */
  17655. _this.shadowEnabled = true;
  17656. _this._excludeWithLayerMask = 0;
  17657. _this._includeOnlyWithLayerMask = 0;
  17658. _this._lightmapMode = 0;
  17659. /**
  17660. * @ignore Internal use only.
  17661. */
  17662. _this._excludedMeshesIds = new Array();
  17663. /**
  17664. * @ignore Internal use only.
  17665. */
  17666. _this._includedOnlyMeshesIds = new Array();
  17667. _this.getScene().addLight(_this);
  17668. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17669. _this._buildUniformLayout();
  17670. _this.includedOnlyMeshes = new Array();
  17671. _this.excludedMeshes = new Array();
  17672. _this._resyncMeshes();
  17673. return _this;
  17674. }
  17675. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17676. /**
  17677. * If every light affecting the material is in this lightmapMode,
  17678. * material.lightmapTexture adds or multiplies
  17679. * (depends on material.useLightmapAsShadowmap)
  17680. * after every other light calculations.
  17681. */
  17682. get: function () {
  17683. return Light._LIGHTMAP_DEFAULT;
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17689. /**
  17690. * material.lightmapTexture as only diffuse lighting from this light
  17691. * adds only specular lighting from this light
  17692. * adds dynamic shadows
  17693. */
  17694. get: function () {
  17695. return Light._LIGHTMAP_SPECULAR;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17701. /**
  17702. * material.lightmapTexture as only lighting
  17703. * no light calculation from this light
  17704. * only adds dynamic shadows from this light
  17705. */
  17706. get: function () {
  17707. return Light._LIGHTMAP_SHADOWSONLY;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17713. /**
  17714. * Each light type uses the default quantity according to its type:
  17715. * point/spot lights use luminous intensity
  17716. * directional lights use illuminance
  17717. */
  17718. get: function () {
  17719. return Light._INTENSITYMODE_AUTOMATIC;
  17720. },
  17721. enumerable: true,
  17722. configurable: true
  17723. });
  17724. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17725. /**
  17726. * lumen (lm)
  17727. */
  17728. get: function () {
  17729. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17730. },
  17731. enumerable: true,
  17732. configurable: true
  17733. });
  17734. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17735. /**
  17736. * candela (lm/sr)
  17737. */
  17738. get: function () {
  17739. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17740. },
  17741. enumerable: true,
  17742. configurable: true
  17743. });
  17744. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17745. /**
  17746. * lux (lm/m^2)
  17747. */
  17748. get: function () {
  17749. return Light._INTENSITYMODE_ILLUMINANCE;
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17755. /**
  17756. * nit (cd/m^2)
  17757. */
  17758. get: function () {
  17759. return Light._INTENSITYMODE_LUMINANCE;
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17765. /**
  17766. * Light type const id of the point light.
  17767. */
  17768. get: function () {
  17769. return Light._LIGHTTYPEID_POINTLIGHT;
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17775. /**
  17776. * Light type const id of the directional light.
  17777. */
  17778. get: function () {
  17779. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17785. /**
  17786. * Light type const id of the spot light.
  17787. */
  17788. get: function () {
  17789. return Light._LIGHTTYPEID_SPOTLIGHT;
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17795. /**
  17796. * Light type const id of the hemispheric light.
  17797. */
  17798. get: function () {
  17799. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. Object.defineProperty(Light.prototype, "intensityMode", {
  17805. /**
  17806. * Gets the photometric scale used to interpret the intensity.
  17807. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17808. */
  17809. get: function () {
  17810. return this._intensityMode;
  17811. },
  17812. /**
  17813. * Sets the photometric scale used to interpret the intensity.
  17814. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17815. */
  17816. set: function (value) {
  17817. this._intensityMode = value;
  17818. this._computePhotometricScale();
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. ;
  17824. ;
  17825. Object.defineProperty(Light.prototype, "radius", {
  17826. /**
  17827. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17828. */
  17829. get: function () {
  17830. return this._radius;
  17831. },
  17832. /**
  17833. * sets the light radius used by PBR Materials to simulate soft area lights.
  17834. */
  17835. set: function (value) {
  17836. this._radius = value;
  17837. this._computePhotometricScale();
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. ;
  17843. ;
  17844. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17845. /**
  17846. * Gets the only meshes impacted by this light.
  17847. */
  17848. get: function () {
  17849. return this._includedOnlyMeshes;
  17850. },
  17851. /**
  17852. * Sets the only meshes impacted by this light.
  17853. */
  17854. set: function (value) {
  17855. this._includedOnlyMeshes = value;
  17856. this._hookArrayForIncludedOnly(value);
  17857. },
  17858. enumerable: true,
  17859. configurable: true
  17860. });
  17861. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17862. /**
  17863. * Gets the meshes not impacted by this light.
  17864. */
  17865. get: function () {
  17866. return this._excludedMeshes;
  17867. },
  17868. /**
  17869. * Sets the meshes not impacted by this light.
  17870. */
  17871. set: function (value) {
  17872. this._excludedMeshes = value;
  17873. this._hookArrayForExcluded(value);
  17874. },
  17875. enumerable: true,
  17876. configurable: true
  17877. });
  17878. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17879. /**
  17880. * Gets the layer id use to find what meshes are not impacted by the light.
  17881. * Inactive if 0
  17882. */
  17883. get: function () {
  17884. return this._excludeWithLayerMask;
  17885. },
  17886. /**
  17887. * Sets the layer id use to find what meshes are not impacted by the light.
  17888. * Inactive if 0
  17889. */
  17890. set: function (value) {
  17891. this._excludeWithLayerMask = value;
  17892. this._resyncMeshes();
  17893. },
  17894. enumerable: true,
  17895. configurable: true
  17896. });
  17897. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17898. /**
  17899. * Gets the layer id use to find what meshes are impacted by the light.
  17900. * Inactive if 0
  17901. */
  17902. get: function () {
  17903. return this._includeOnlyWithLayerMask;
  17904. },
  17905. /**
  17906. * Sets the layer id use to find what meshes are impacted by the light.
  17907. * Inactive if 0
  17908. */
  17909. set: function (value) {
  17910. this._includeOnlyWithLayerMask = value;
  17911. this._resyncMeshes();
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(Light.prototype, "lightmapMode", {
  17917. /**
  17918. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17919. */
  17920. get: function () {
  17921. return this._lightmapMode;
  17922. },
  17923. /**
  17924. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17925. */
  17926. set: function (value) {
  17927. if (this._lightmapMode === value) {
  17928. return;
  17929. }
  17930. this._lightmapMode = value;
  17931. this._markMeshesAsLightDirty();
  17932. },
  17933. enumerable: true,
  17934. configurable: true
  17935. });
  17936. /**
  17937. * Returns the string "Light".
  17938. * @returns the class name
  17939. */
  17940. Light.prototype.getClassName = function () {
  17941. return "Light";
  17942. };
  17943. /**
  17944. * Converts the light information to a readable string for debug purpose.
  17945. * @param fullDetails Supports for multiple levels of logging within scene loading
  17946. * @returns the human readable light info
  17947. */
  17948. Light.prototype.toString = function (fullDetails) {
  17949. var ret = "Name: " + this.name;
  17950. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17951. if (this.animations) {
  17952. for (var i = 0; i < this.animations.length; i++) {
  17953. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17954. }
  17955. }
  17956. if (fullDetails) {
  17957. }
  17958. return ret;
  17959. };
  17960. /**
  17961. * Set the enabled state of this node.
  17962. * @param value - the new enabled state
  17963. * @see isEnabled
  17964. */
  17965. Light.prototype.setEnabled = function (value) {
  17966. _super.prototype.setEnabled.call(this, value);
  17967. this._resyncMeshes();
  17968. };
  17969. /**
  17970. * Returns the Light associated shadow generator if any.
  17971. * @return the associated shadow generator.
  17972. */
  17973. Light.prototype.getShadowGenerator = function () {
  17974. return this._shadowGenerator;
  17975. };
  17976. /**
  17977. * Returns a Vector3, the absolute light position in the World.
  17978. * @returns the world space position of the light
  17979. */
  17980. Light.prototype.getAbsolutePosition = function () {
  17981. return BABYLON.Vector3.Zero();
  17982. };
  17983. /**
  17984. * Specifies if the light will affect the passed mesh.
  17985. * @param mesh The mesh to test against the light
  17986. * @return true the mesh is affected otherwise, false.
  17987. */
  17988. Light.prototype.canAffectMesh = function (mesh) {
  17989. if (!mesh) {
  17990. return true;
  17991. }
  17992. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17993. return false;
  17994. }
  17995. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17996. return false;
  17997. }
  17998. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17999. return false;
  18000. }
  18001. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18002. return false;
  18003. }
  18004. return true;
  18005. };
  18006. /**
  18007. * Computes and Returns the light World matrix.
  18008. * @returns the world matrix
  18009. */
  18010. Light.prototype.getWorldMatrix = function () {
  18011. this._currentRenderId = this.getScene().getRenderId();
  18012. var worldMatrix = this._getWorldMatrix();
  18013. if (this.parent && this.parent.getWorldMatrix) {
  18014. if (!this._parentedWorldMatrix) {
  18015. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18016. }
  18017. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18018. this._markSyncedWithParent();
  18019. return this._parentedWorldMatrix;
  18020. }
  18021. return worldMatrix;
  18022. };
  18023. /**
  18024. * Sort function to order lights for rendering.
  18025. * @param a First Light object to compare to second.
  18026. * @param b Second Light object to compare first.
  18027. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18028. */
  18029. Light.CompareLightsPriority = function (a, b) {
  18030. //shadow-casting lights have priority over non-shadow-casting lights
  18031. //the renderPrioirty is a secondary sort criterion
  18032. if (a.shadowEnabled !== b.shadowEnabled) {
  18033. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18034. }
  18035. return b.renderPriority - a.renderPriority;
  18036. };
  18037. /**
  18038. * Disposes the light.
  18039. */
  18040. Light.prototype.dispose = function () {
  18041. if (this._shadowGenerator) {
  18042. this._shadowGenerator.dispose();
  18043. this._shadowGenerator = null;
  18044. }
  18045. // Animations
  18046. this.getScene().stopAnimation(this);
  18047. // Remove from meshes
  18048. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18049. var mesh = _a[_i];
  18050. mesh._removeLightSource(this);
  18051. }
  18052. this._uniformBuffer.dispose();
  18053. // Remove from scene
  18054. this.getScene().removeLight(this);
  18055. _super.prototype.dispose.call(this);
  18056. };
  18057. /**
  18058. * Returns the light type ID (integer).
  18059. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18060. */
  18061. Light.prototype.getTypeID = function () {
  18062. return 0;
  18063. };
  18064. /**
  18065. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18066. * @returns the scaled intensity in intensity mode unit
  18067. */
  18068. Light.prototype.getScaledIntensity = function () {
  18069. return this._photometricScale * this.intensity;
  18070. };
  18071. /**
  18072. * Returns a new Light object, named "name", from the current one.
  18073. * @param name The name of the cloned light
  18074. * @returns the new created light
  18075. */
  18076. Light.prototype.clone = function (name) {
  18077. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18078. if (!constructor) {
  18079. return null;
  18080. }
  18081. return BABYLON.SerializationHelper.Clone(constructor, this);
  18082. };
  18083. /**
  18084. * Serializes the current light into a Serialization object.
  18085. * @returns the serialized object.
  18086. */
  18087. Light.prototype.serialize = function () {
  18088. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18089. // Type
  18090. serializationObject.type = this.getTypeID();
  18091. // Parent
  18092. if (this.parent) {
  18093. serializationObject.parentId = this.parent.id;
  18094. }
  18095. // Inclusion / exclusions
  18096. if (this.excludedMeshes.length > 0) {
  18097. serializationObject.excludedMeshesIds = [];
  18098. this.excludedMeshes.forEach(function (mesh) {
  18099. serializationObject.excludedMeshesIds.push(mesh.id);
  18100. });
  18101. }
  18102. if (this.includedOnlyMeshes.length > 0) {
  18103. serializationObject.includedOnlyMeshesIds = [];
  18104. this.includedOnlyMeshes.forEach(function (mesh) {
  18105. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18106. });
  18107. }
  18108. // Animations
  18109. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18110. serializationObject.ranges = this.serializeAnimationRanges();
  18111. return serializationObject;
  18112. };
  18113. /**
  18114. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18115. * This new light is named "name" and added to the passed scene.
  18116. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18117. * @param name The friendly name of the light
  18118. * @param scene The scene the new light will belong to
  18119. * @returns the constructor function
  18120. */
  18121. Light.GetConstructorFromName = function (type, name, scene) {
  18122. switch (type) {
  18123. case 0:
  18124. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18125. case 1:
  18126. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18127. case 2:
  18128. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18129. case 3:
  18130. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18131. }
  18132. return null;
  18133. };
  18134. /**
  18135. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18136. * @param parsedLight The JSON representation of the light
  18137. * @param scene The scene to create the parsed light in
  18138. * @returns the created light after parsing
  18139. */
  18140. Light.Parse = function (parsedLight, scene) {
  18141. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18142. if (!constructor) {
  18143. return null;
  18144. }
  18145. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18146. // Inclusion / exclusions
  18147. if (parsedLight.excludedMeshesIds) {
  18148. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18149. }
  18150. if (parsedLight.includedOnlyMeshesIds) {
  18151. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18152. }
  18153. // Parent
  18154. if (parsedLight.parentId) {
  18155. light._waitingParentId = parsedLight.parentId;
  18156. }
  18157. // Animations
  18158. if (parsedLight.animations) {
  18159. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18160. var parsedAnimation = parsedLight.animations[animationIndex];
  18161. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18162. }
  18163. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18164. }
  18165. if (parsedLight.autoAnimate) {
  18166. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18167. }
  18168. return light;
  18169. };
  18170. Light.prototype._hookArrayForExcluded = function (array) {
  18171. var _this = this;
  18172. var oldPush = array.push;
  18173. array.push = function () {
  18174. var items = [];
  18175. for (var _i = 0; _i < arguments.length; _i++) {
  18176. items[_i] = arguments[_i];
  18177. }
  18178. var result = oldPush.apply(array, items);
  18179. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18180. var item = items_1[_a];
  18181. item._resyncLighSource(_this);
  18182. }
  18183. return result;
  18184. };
  18185. var oldSplice = array.splice;
  18186. array.splice = function (index, deleteCount) {
  18187. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18188. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18189. var item = deleted_1[_i];
  18190. item._resyncLighSource(_this);
  18191. }
  18192. return deleted;
  18193. };
  18194. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18195. var item = array_1[_i];
  18196. item._resyncLighSource(this);
  18197. }
  18198. };
  18199. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18200. var _this = this;
  18201. var oldPush = array.push;
  18202. array.push = function () {
  18203. var items = [];
  18204. for (var _i = 0; _i < arguments.length; _i++) {
  18205. items[_i] = arguments[_i];
  18206. }
  18207. var result = oldPush.apply(array, items);
  18208. _this._resyncMeshes();
  18209. return result;
  18210. };
  18211. var oldSplice = array.splice;
  18212. array.splice = function (index, deleteCount) {
  18213. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18214. _this._resyncMeshes();
  18215. return deleted;
  18216. };
  18217. this._resyncMeshes();
  18218. };
  18219. Light.prototype._resyncMeshes = function () {
  18220. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18221. var mesh = _a[_i];
  18222. mesh._resyncLighSource(this);
  18223. }
  18224. };
  18225. /**
  18226. * Forces the meshes to update their light related information in their rendering used effects
  18227. * @ignore Internal Use Only
  18228. */
  18229. Light.prototype._markMeshesAsLightDirty = function () {
  18230. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18231. var mesh = _a[_i];
  18232. if (mesh._lightSources.indexOf(this) !== -1) {
  18233. mesh._markSubMeshesAsLightDirty();
  18234. }
  18235. }
  18236. };
  18237. /**
  18238. * Recomputes the cached photometric scale if needed.
  18239. */
  18240. Light.prototype._computePhotometricScale = function () {
  18241. this._photometricScale = this._getPhotometricScale();
  18242. this.getScene().resetCachedMaterial();
  18243. };
  18244. /**
  18245. * Returns the Photometric Scale according to the light type and intensity mode.
  18246. */
  18247. Light.prototype._getPhotometricScale = function () {
  18248. var photometricScale = 0.0;
  18249. var lightTypeID = this.getTypeID();
  18250. //get photometric mode
  18251. var photometricMode = this.intensityMode;
  18252. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18253. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18254. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18255. }
  18256. else {
  18257. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18258. }
  18259. }
  18260. //compute photometric scale
  18261. switch (lightTypeID) {
  18262. case Light.LIGHTTYPEID_POINTLIGHT:
  18263. case Light.LIGHTTYPEID_SPOTLIGHT:
  18264. switch (photometricMode) {
  18265. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18266. photometricScale = 1.0 / (4.0 * Math.PI);
  18267. break;
  18268. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18269. photometricScale = 1.0;
  18270. break;
  18271. case Light.INTENSITYMODE_LUMINANCE:
  18272. photometricScale = this.radius * this.radius;
  18273. break;
  18274. }
  18275. break;
  18276. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18277. switch (photometricMode) {
  18278. case Light.INTENSITYMODE_ILLUMINANCE:
  18279. photometricScale = 1.0;
  18280. break;
  18281. case Light.INTENSITYMODE_LUMINANCE:
  18282. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18283. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18284. var apexAngleRadians = this.radius;
  18285. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18286. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18287. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18288. photometricScale = solidAngle;
  18289. break;
  18290. }
  18291. break;
  18292. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18293. // No fall off in hemisperic light.
  18294. photometricScale = 1.0;
  18295. break;
  18296. }
  18297. return photometricScale;
  18298. };
  18299. /**
  18300. * Reorder the light in the scene according to their defined priority.
  18301. * @ignore Internal Use Only
  18302. */
  18303. Light.prototype._reorderLightsInScene = function () {
  18304. var scene = this.getScene();
  18305. if (this._renderPriority != 0) {
  18306. scene.requireLightSorting = true;
  18307. }
  18308. this.getScene().sortLightsByPriority();
  18309. };
  18310. //lightmapMode Consts
  18311. Light._LIGHTMAP_DEFAULT = 0;
  18312. Light._LIGHTMAP_SPECULAR = 1;
  18313. Light._LIGHTMAP_SHADOWSONLY = 2;
  18314. // Intensity Mode Consts
  18315. Light._INTENSITYMODE_AUTOMATIC = 0;
  18316. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18317. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18318. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18319. Light._INTENSITYMODE_LUMINANCE = 4;
  18320. // Light types ids const.
  18321. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18322. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18323. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18324. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18325. __decorate([
  18326. BABYLON.serializeAsColor3()
  18327. ], Light.prototype, "diffuse", void 0);
  18328. __decorate([
  18329. BABYLON.serializeAsColor3()
  18330. ], Light.prototype, "specular", void 0);
  18331. __decorate([
  18332. BABYLON.serialize()
  18333. ], Light.prototype, "intensity", void 0);
  18334. __decorate([
  18335. BABYLON.serialize()
  18336. ], Light.prototype, "range", void 0);
  18337. __decorate([
  18338. BABYLON.serialize()
  18339. ], Light.prototype, "intensityMode", null);
  18340. __decorate([
  18341. BABYLON.serialize()
  18342. ], Light.prototype, "radius", null);
  18343. __decorate([
  18344. BABYLON.serialize()
  18345. ], Light.prototype, "_renderPriority", void 0);
  18346. __decorate([
  18347. BABYLON.expandToProperty("_reorderLightsInScene")
  18348. ], Light.prototype, "renderPriority", void 0);
  18349. __decorate([
  18350. BABYLON.serialize()
  18351. ], Light.prototype, "shadowEnabled", void 0);
  18352. __decorate([
  18353. BABYLON.serialize("excludeWithLayerMask")
  18354. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18355. __decorate([
  18356. BABYLON.serialize("includeOnlyWithLayerMask")
  18357. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18358. __decorate([
  18359. BABYLON.serialize("lightmapMode")
  18360. ], Light.prototype, "_lightmapMode", void 0);
  18361. return Light;
  18362. }(BABYLON.Node));
  18363. BABYLON.Light = Light;
  18364. })(BABYLON || (BABYLON = {}));
  18365. //# sourceMappingURL=babylon.light.js.map
  18366. var BABYLON;
  18367. (function (BABYLON) {
  18368. var Camera = /** @class */ (function (_super) {
  18369. __extends(Camera, _super);
  18370. function Camera(name, position, scene) {
  18371. var _this = _super.call(this, name, scene) || this;
  18372. /**
  18373. * The vector the camera should consider as up.
  18374. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18375. */
  18376. _this.upVector = BABYLON.Vector3.Up();
  18377. _this.orthoLeft = null;
  18378. _this.orthoRight = null;
  18379. _this.orthoBottom = null;
  18380. _this.orthoTop = null;
  18381. /**
  18382. * FOV is set in Radians. (default is 0.8)
  18383. */
  18384. _this.fov = 0.8;
  18385. _this.minZ = 1;
  18386. _this.maxZ = 10000.0;
  18387. _this.inertia = 0.9;
  18388. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18389. _this.isIntermediate = false;
  18390. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18391. /**
  18392. * Restricts the camera to viewing objects with the same layerMask.
  18393. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18394. */
  18395. _this.layerMask = 0x0FFFFFFF;
  18396. /**
  18397. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18398. */
  18399. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18400. // Camera rig members
  18401. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18402. _this._rigCameras = new Array();
  18403. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18404. _this._skipRendering = false;
  18405. _this.customRenderTargets = new Array();
  18406. // Observables
  18407. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18408. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18409. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18410. _this.onRestoreStateObservable = new BABYLON.Observable();
  18411. // Cache
  18412. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18413. _this._projectionMatrix = new BABYLON.Matrix();
  18414. _this._doNotComputeProjectionMatrix = false;
  18415. _this._postProcesses = new Array();
  18416. _this._transformMatrix = BABYLON.Matrix.Zero();
  18417. _this._activeMeshes = new BABYLON.SmartArray(256);
  18418. _this._globalPosition = BABYLON.Vector3.Zero();
  18419. _this._refreshFrustumPlanes = true;
  18420. _this.getScene().addCamera(_this);
  18421. if (!_this.getScene().activeCamera) {
  18422. _this.getScene().activeCamera = _this;
  18423. }
  18424. _this.position = position;
  18425. return _this;
  18426. }
  18427. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18428. get: function () {
  18429. return Camera._PERSPECTIVE_CAMERA;
  18430. },
  18431. enumerable: true,
  18432. configurable: true
  18433. });
  18434. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18435. get: function () {
  18436. return Camera._ORTHOGRAPHIC_CAMERA;
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18442. /**
  18443. * This is the default FOV mode for perspective cameras.
  18444. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18445. *
  18446. */
  18447. get: function () {
  18448. return Camera._FOVMODE_VERTICAL_FIXED;
  18449. },
  18450. enumerable: true,
  18451. configurable: true
  18452. });
  18453. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18454. /**
  18455. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18456. *
  18457. */
  18458. get: function () {
  18459. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18460. },
  18461. enumerable: true,
  18462. configurable: true
  18463. });
  18464. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18465. get: function () {
  18466. return Camera._RIG_MODE_NONE;
  18467. },
  18468. enumerable: true,
  18469. configurable: true
  18470. });
  18471. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18472. get: function () {
  18473. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18474. },
  18475. enumerable: true,
  18476. configurable: true
  18477. });
  18478. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18479. get: function () {
  18480. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18481. },
  18482. enumerable: true,
  18483. configurable: true
  18484. });
  18485. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18486. get: function () {
  18487. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18493. get: function () {
  18494. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18495. },
  18496. enumerable: true,
  18497. configurable: true
  18498. });
  18499. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18500. get: function () {
  18501. return Camera._RIG_MODE_VR;
  18502. },
  18503. enumerable: true,
  18504. configurable: true
  18505. });
  18506. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18507. get: function () {
  18508. return Camera._RIG_MODE_WEBVR;
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. /**
  18514. * Store current camera state (fov, position, etc..)
  18515. */
  18516. Camera.prototype.storeState = function () {
  18517. this._stateStored = true;
  18518. this._storedFov = this.fov;
  18519. return this;
  18520. };
  18521. /**
  18522. * Restores the camera state values if it has been stored. You must call storeState() first
  18523. */
  18524. Camera.prototype._restoreStateValues = function () {
  18525. if (!this._stateStored) {
  18526. return false;
  18527. }
  18528. this.fov = this._storedFov;
  18529. return true;
  18530. };
  18531. /**
  18532. * Restored camera state. You must call storeState() first
  18533. */
  18534. Camera.prototype.restoreState = function () {
  18535. if (this._restoreStateValues()) {
  18536. this.onRestoreStateObservable.notifyObservers(this);
  18537. return true;
  18538. }
  18539. return false;
  18540. };
  18541. Camera.prototype.getClassName = function () {
  18542. return "Camera";
  18543. };
  18544. /**
  18545. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18546. */
  18547. Camera.prototype.toString = function (fullDetails) {
  18548. var ret = "Name: " + this.name;
  18549. ret += ", type: " + this.getClassName();
  18550. if (this.animations) {
  18551. for (var i = 0; i < this.animations.length; i++) {
  18552. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18553. }
  18554. }
  18555. if (fullDetails) {
  18556. }
  18557. return ret;
  18558. };
  18559. Object.defineProperty(Camera.prototype, "globalPosition", {
  18560. get: function () {
  18561. return this._globalPosition;
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Camera.prototype.getActiveMeshes = function () {
  18567. return this._activeMeshes;
  18568. };
  18569. Camera.prototype.isActiveMesh = function (mesh) {
  18570. return (this._activeMeshes.indexOf(mesh) !== -1);
  18571. };
  18572. //Cache
  18573. Camera.prototype._initCache = function () {
  18574. _super.prototype._initCache.call(this);
  18575. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18576. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18577. this._cache.mode = undefined;
  18578. this._cache.minZ = undefined;
  18579. this._cache.maxZ = undefined;
  18580. this._cache.fov = undefined;
  18581. this._cache.fovMode = undefined;
  18582. this._cache.aspectRatio = undefined;
  18583. this._cache.orthoLeft = undefined;
  18584. this._cache.orthoRight = undefined;
  18585. this._cache.orthoBottom = undefined;
  18586. this._cache.orthoTop = undefined;
  18587. this._cache.renderWidth = undefined;
  18588. this._cache.renderHeight = undefined;
  18589. };
  18590. Camera.prototype._updateCache = function (ignoreParentClass) {
  18591. if (!ignoreParentClass) {
  18592. _super.prototype._updateCache.call(this);
  18593. }
  18594. this._cache.position.copyFrom(this.position);
  18595. this._cache.upVector.copyFrom(this.upVector);
  18596. };
  18597. // Synchronized
  18598. Camera.prototype._isSynchronized = function () {
  18599. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18600. };
  18601. Camera.prototype._isSynchronizedViewMatrix = function () {
  18602. if (!_super.prototype._isSynchronized.call(this))
  18603. return false;
  18604. return this._cache.position.equals(this.position)
  18605. && this._cache.upVector.equals(this.upVector)
  18606. && this.isSynchronizedWithParent();
  18607. };
  18608. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18609. var check = this._cache.mode === this.mode
  18610. && this._cache.minZ === this.minZ
  18611. && this._cache.maxZ === this.maxZ;
  18612. if (!check) {
  18613. return false;
  18614. }
  18615. var engine = this.getEngine();
  18616. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18617. check = this._cache.fov === this.fov
  18618. && this._cache.fovMode === this.fovMode
  18619. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18620. }
  18621. else {
  18622. check = this._cache.orthoLeft === this.orthoLeft
  18623. && this._cache.orthoRight === this.orthoRight
  18624. && this._cache.orthoBottom === this.orthoBottom
  18625. && this._cache.orthoTop === this.orthoTop
  18626. && this._cache.renderWidth === engine.getRenderWidth()
  18627. && this._cache.renderHeight === engine.getRenderHeight();
  18628. }
  18629. return check;
  18630. };
  18631. // Controls
  18632. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18633. };
  18634. Camera.prototype.detachControl = function (element) {
  18635. };
  18636. Camera.prototype.update = function () {
  18637. this._checkInputs();
  18638. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18639. this._updateRigCameras();
  18640. }
  18641. };
  18642. Camera.prototype._checkInputs = function () {
  18643. this.onAfterCheckInputsObservable.notifyObservers(this);
  18644. };
  18645. Object.defineProperty(Camera.prototype, "rigCameras", {
  18646. get: function () {
  18647. return this._rigCameras;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18653. get: function () {
  18654. return this._rigPostProcess;
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18660. // invalidate framebuffer
  18661. if (this._postProcesses.length > 0) {
  18662. this._postProcesses[0].markTextureDirty();
  18663. }
  18664. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18665. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18666. var cam = this._rigCameras[i];
  18667. var rigPostProcess = cam._rigPostProcess;
  18668. // for VR rig, there does not have to be a post process
  18669. if (rigPostProcess) {
  18670. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18671. if (isPass) {
  18672. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18673. cam.isIntermediate = this._postProcesses.length === 0;
  18674. }
  18675. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18676. rigPostProcess.markTextureDirty();
  18677. }
  18678. else {
  18679. cam._postProcesses = this._postProcesses.slice(0);
  18680. }
  18681. }
  18682. };
  18683. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18684. if (insertAt === void 0) { insertAt = null; }
  18685. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18686. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18687. return 0;
  18688. }
  18689. if (insertAt == null || insertAt < 0) {
  18690. this._postProcesses.push(postProcess);
  18691. }
  18692. else {
  18693. this._postProcesses.splice(insertAt, 0, postProcess);
  18694. }
  18695. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18696. return this._postProcesses.indexOf(postProcess);
  18697. };
  18698. Camera.prototype.detachPostProcess = function (postProcess) {
  18699. var idx = this._postProcesses.indexOf(postProcess);
  18700. if (idx !== -1) {
  18701. this._postProcesses.splice(idx, 1);
  18702. }
  18703. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18704. };
  18705. Camera.prototype.getWorldMatrix = function () {
  18706. if (!this._worldMatrix) {
  18707. this._worldMatrix = BABYLON.Matrix.Identity();
  18708. }
  18709. var viewMatrix = this.getViewMatrix();
  18710. viewMatrix.invertToRef(this._worldMatrix);
  18711. return this._worldMatrix;
  18712. };
  18713. Camera.prototype._getViewMatrix = function () {
  18714. return BABYLON.Matrix.Identity();
  18715. };
  18716. Camera.prototype.getViewMatrix = function (force) {
  18717. if (!force && this._isSynchronizedViewMatrix()) {
  18718. return this._computedViewMatrix;
  18719. }
  18720. this.updateCache();
  18721. this._computedViewMatrix = this._getViewMatrix();
  18722. this._currentRenderId = this.getScene().getRenderId();
  18723. this._refreshFrustumPlanes = true;
  18724. if (!this.parent || !this.parent.getWorldMatrix) {
  18725. this._globalPosition.copyFrom(this.position);
  18726. }
  18727. else {
  18728. if (!this._worldMatrix) {
  18729. this._worldMatrix = BABYLON.Matrix.Identity();
  18730. }
  18731. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18732. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18733. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18734. this._computedViewMatrix.invert();
  18735. this._markSyncedWithParent();
  18736. }
  18737. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18738. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18739. }
  18740. this.onViewMatrixChangedObservable.notifyObservers(this);
  18741. return this._computedViewMatrix;
  18742. };
  18743. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18744. this._doNotComputeProjectionMatrix = true;
  18745. if (projection !== undefined) {
  18746. this._projectionMatrix = projection;
  18747. }
  18748. };
  18749. ;
  18750. Camera.prototype.unfreezeProjectionMatrix = function () {
  18751. this._doNotComputeProjectionMatrix = false;
  18752. };
  18753. ;
  18754. Camera.prototype.getProjectionMatrix = function (force) {
  18755. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18756. return this._projectionMatrix;
  18757. }
  18758. // Cache
  18759. this._cache.mode = this.mode;
  18760. this._cache.minZ = this.minZ;
  18761. this._cache.maxZ = this.maxZ;
  18762. // Matrix
  18763. this._refreshFrustumPlanes = true;
  18764. var engine = this.getEngine();
  18765. var scene = this.getScene();
  18766. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18767. this._cache.fov = this.fov;
  18768. this._cache.fovMode = this.fovMode;
  18769. this._cache.aspectRatio = engine.getAspectRatio(this);
  18770. if (this.minZ <= 0) {
  18771. this.minZ = 0.1;
  18772. }
  18773. if (scene.useRightHandedSystem) {
  18774. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18775. }
  18776. else {
  18777. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18778. }
  18779. }
  18780. else {
  18781. var halfWidth = engine.getRenderWidth() / 2.0;
  18782. var halfHeight = engine.getRenderHeight() / 2.0;
  18783. if (scene.useRightHandedSystem) {
  18784. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18785. }
  18786. else {
  18787. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18788. }
  18789. this._cache.orthoLeft = this.orthoLeft;
  18790. this._cache.orthoRight = this.orthoRight;
  18791. this._cache.orthoBottom = this.orthoBottom;
  18792. this._cache.orthoTop = this.orthoTop;
  18793. this._cache.renderWidth = engine.getRenderWidth();
  18794. this._cache.renderHeight = engine.getRenderHeight();
  18795. }
  18796. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18797. return this._projectionMatrix;
  18798. };
  18799. Camera.prototype.getTranformationMatrix = function () {
  18800. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18801. return this._transformMatrix;
  18802. };
  18803. Camera.prototype.updateFrustumPlanes = function () {
  18804. if (!this._refreshFrustumPlanes) {
  18805. return;
  18806. }
  18807. this.getTranformationMatrix();
  18808. if (!this._frustumPlanes) {
  18809. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18810. }
  18811. else {
  18812. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18813. }
  18814. this._refreshFrustumPlanes = false;
  18815. };
  18816. Camera.prototype.isInFrustum = function (target) {
  18817. this.updateFrustumPlanes();
  18818. return target.isInFrustum(this._frustumPlanes);
  18819. };
  18820. Camera.prototype.isCompletelyInFrustum = function (target) {
  18821. this.updateFrustumPlanes();
  18822. return target.isCompletelyInFrustum(this._frustumPlanes);
  18823. };
  18824. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18825. if (length === void 0) { length = 100; }
  18826. if (!transform) {
  18827. transform = this.getWorldMatrix();
  18828. }
  18829. if (!origin) {
  18830. origin = this.position;
  18831. }
  18832. var forward = new BABYLON.Vector3(0, 0, 1);
  18833. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18834. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18835. return new BABYLON.Ray(origin, direction, length);
  18836. };
  18837. Camera.prototype.dispose = function () {
  18838. // Observables
  18839. this.onViewMatrixChangedObservable.clear();
  18840. this.onProjectionMatrixChangedObservable.clear();
  18841. this.onAfterCheckInputsObservable.clear();
  18842. this.onRestoreStateObservable.clear();
  18843. // Inputs
  18844. if (this.inputs) {
  18845. this.inputs.clear();
  18846. }
  18847. // Animations
  18848. this.getScene().stopAnimation(this);
  18849. // Remove from scene
  18850. this.getScene().removeCamera(this);
  18851. while (this._rigCameras.length > 0) {
  18852. var camera = this._rigCameras.pop();
  18853. if (camera) {
  18854. camera.dispose();
  18855. }
  18856. }
  18857. // Postprocesses
  18858. if (this._rigPostProcess) {
  18859. this._rigPostProcess.dispose(this);
  18860. this._rigPostProcess = null;
  18861. this._postProcesses = [];
  18862. }
  18863. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18864. this._rigPostProcess = null;
  18865. this._postProcesses = [];
  18866. }
  18867. else {
  18868. var i = this._postProcesses.length;
  18869. while (--i >= 0) {
  18870. this._postProcesses[i].dispose(this);
  18871. }
  18872. }
  18873. // Render targets
  18874. var i = this.customRenderTargets.length;
  18875. while (--i >= 0) {
  18876. this.customRenderTargets[i].dispose();
  18877. }
  18878. this.customRenderTargets = [];
  18879. // Active Meshes
  18880. this._activeMeshes.dispose();
  18881. _super.prototype.dispose.call(this);
  18882. };
  18883. Object.defineProperty(Camera.prototype, "leftCamera", {
  18884. // ---- Camera rigs section ----
  18885. get: function () {
  18886. if (this._rigCameras.length < 1) {
  18887. return null;
  18888. }
  18889. return this._rigCameras[0];
  18890. },
  18891. enumerable: true,
  18892. configurable: true
  18893. });
  18894. Object.defineProperty(Camera.prototype, "rightCamera", {
  18895. get: function () {
  18896. if (this._rigCameras.length < 2) {
  18897. return null;
  18898. }
  18899. return this._rigCameras[1];
  18900. },
  18901. enumerable: true,
  18902. configurable: true
  18903. });
  18904. Camera.prototype.getLeftTarget = function () {
  18905. if (this._rigCameras.length < 1) {
  18906. return null;
  18907. }
  18908. return this._rigCameras[0].getTarget();
  18909. };
  18910. Camera.prototype.getRightTarget = function () {
  18911. if (this._rigCameras.length < 2) {
  18912. return null;
  18913. }
  18914. return this._rigCameras[1].getTarget();
  18915. };
  18916. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18917. if (this.cameraRigMode === mode) {
  18918. return;
  18919. }
  18920. while (this._rigCameras.length > 0) {
  18921. var camera = this._rigCameras.pop();
  18922. if (camera) {
  18923. camera.dispose();
  18924. }
  18925. }
  18926. this.cameraRigMode = mode;
  18927. this._cameraRigParams = {};
  18928. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18929. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18930. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18931. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18932. // create the rig cameras, unless none
  18933. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18934. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18935. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18936. if (leftCamera && rightCamera) {
  18937. this._rigCameras.push(leftCamera);
  18938. this._rigCameras.push(rightCamera);
  18939. }
  18940. }
  18941. switch (this.cameraRigMode) {
  18942. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18943. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18944. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18945. break;
  18946. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18947. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18948. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18949. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18950. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18951. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18952. break;
  18953. case Camera.RIG_MODE_VR:
  18954. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18955. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18956. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18957. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18958. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18959. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18960. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18961. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18962. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18963. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18964. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18965. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18966. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18967. if (metrics.compensateDistortion) {
  18968. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18969. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18970. }
  18971. break;
  18972. case Camera.RIG_MODE_WEBVR:
  18973. if (rigParams.vrDisplay) {
  18974. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18975. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18976. //Left eye
  18977. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18978. this._rigCameras[0].setCameraRigParameter("left", true);
  18979. //leaving this for future reference
  18980. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18981. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18982. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18983. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18984. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18985. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18986. this._rigCameras[0].parent = this;
  18987. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18988. //Right eye
  18989. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18990. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18991. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18992. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18993. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18994. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18995. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18996. this._rigCameras[1].parent = this;
  18997. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18998. if (Camera.UseAlternateWebVRRendering) {
  18999. this._rigCameras[1]._skipRendering = true;
  19000. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19001. }
  19002. }
  19003. break;
  19004. }
  19005. this._cascadePostProcessesToRigCams();
  19006. this.update();
  19007. };
  19008. Camera.prototype._getVRProjectionMatrix = function () {
  19009. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19010. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19011. return this._projectionMatrix;
  19012. };
  19013. Camera.prototype._updateCameraRotationMatrix = function () {
  19014. //Here for WebVR
  19015. };
  19016. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19017. //Here for WebVR
  19018. };
  19019. /**
  19020. * This function MUST be overwritten by the different WebVR cameras available.
  19021. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19022. */
  19023. Camera.prototype._getWebVRProjectionMatrix = function () {
  19024. return BABYLON.Matrix.Identity();
  19025. };
  19026. /**
  19027. * This function MUST be overwritten by the different WebVR cameras available.
  19028. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19029. */
  19030. Camera.prototype._getWebVRViewMatrix = function () {
  19031. return BABYLON.Matrix.Identity();
  19032. };
  19033. Camera.prototype.setCameraRigParameter = function (name, value) {
  19034. if (!this._cameraRigParams) {
  19035. this._cameraRigParams = {};
  19036. }
  19037. this._cameraRigParams[name] = value;
  19038. //provisionnally:
  19039. if (name === "interaxialDistance") {
  19040. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19041. }
  19042. };
  19043. /**
  19044. * needs to be overridden by children so sub has required properties to be copied
  19045. */
  19046. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19047. return null;
  19048. };
  19049. /**
  19050. * May need to be overridden by children
  19051. */
  19052. Camera.prototype._updateRigCameras = function () {
  19053. for (var i = 0; i < this._rigCameras.length; i++) {
  19054. this._rigCameras[i].minZ = this.minZ;
  19055. this._rigCameras[i].maxZ = this.maxZ;
  19056. this._rigCameras[i].fov = this.fov;
  19057. }
  19058. // only update viewport when ANAGLYPH
  19059. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19060. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19061. }
  19062. };
  19063. Camera.prototype._setupInputs = function () {
  19064. };
  19065. Camera.prototype.serialize = function () {
  19066. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19067. // Type
  19068. serializationObject.type = this.getClassName();
  19069. // Parent
  19070. if (this.parent) {
  19071. serializationObject.parentId = this.parent.id;
  19072. }
  19073. if (this.inputs) {
  19074. this.inputs.serialize(serializationObject);
  19075. }
  19076. // Animations
  19077. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19078. serializationObject.ranges = this.serializeAnimationRanges();
  19079. return serializationObject;
  19080. };
  19081. Camera.prototype.clone = function (name) {
  19082. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19083. };
  19084. Camera.prototype.getDirection = function (localAxis) {
  19085. var result = BABYLON.Vector3.Zero();
  19086. this.getDirectionToRef(localAxis, result);
  19087. return result;
  19088. };
  19089. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19090. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19091. };
  19092. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19093. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19094. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19095. switch (type) {
  19096. case "ArcRotateCamera":
  19097. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19098. case "DeviceOrientationCamera":
  19099. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19100. case "FollowCamera":
  19101. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19102. case "ArcFollowCamera":
  19103. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19104. case "GamepadCamera":
  19105. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19106. case "TouchCamera":
  19107. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19108. case "VirtualJoysticksCamera":
  19109. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19110. case "WebVRFreeCamera":
  19111. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19112. case "WebVRGamepadCamera":
  19113. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19114. case "VRDeviceOrientationFreeCamera":
  19115. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19116. case "VRDeviceOrientationGamepadCamera":
  19117. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19118. case "AnaglyphArcRotateCamera":
  19119. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19120. case "AnaglyphFreeCamera":
  19121. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19122. case "AnaglyphGamepadCamera":
  19123. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19124. case "AnaglyphUniversalCamera":
  19125. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19126. case "StereoscopicArcRotateCamera":
  19127. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19128. case "StereoscopicFreeCamera":
  19129. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19130. case "StereoscopicGamepadCamera":
  19131. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19132. case "StereoscopicUniversalCamera":
  19133. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19134. case "FreeCamera":// Forcing Universal here
  19135. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19136. default:// Universal Camera is the default value
  19137. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19138. }
  19139. };
  19140. Camera.prototype.computeWorldMatrix = function () {
  19141. return this.getWorldMatrix();
  19142. };
  19143. Camera.Parse = function (parsedCamera, scene) {
  19144. var type = parsedCamera.type;
  19145. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19146. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19147. // Parent
  19148. if (parsedCamera.parentId) {
  19149. camera._waitingParentId = parsedCamera.parentId;
  19150. }
  19151. //If camera has an input manager, let it parse inputs settings
  19152. if (camera.inputs) {
  19153. camera.inputs.parse(parsedCamera);
  19154. camera._setupInputs();
  19155. }
  19156. if (camera.setPosition) {
  19157. camera.position.copyFromFloats(0, 0, 0);
  19158. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19159. }
  19160. // Target
  19161. if (parsedCamera.target) {
  19162. if (camera.setTarget) {
  19163. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19164. }
  19165. }
  19166. // Apply 3d rig, when found
  19167. if (parsedCamera.cameraRigMode) {
  19168. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19169. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19170. }
  19171. // Animations
  19172. if (parsedCamera.animations) {
  19173. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19174. var parsedAnimation = parsedCamera.animations[animationIndex];
  19175. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19176. }
  19177. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19178. }
  19179. if (parsedCamera.autoAnimate) {
  19180. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19181. }
  19182. return camera;
  19183. };
  19184. // Statics
  19185. Camera._PERSPECTIVE_CAMERA = 0;
  19186. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19187. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19188. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19189. Camera._RIG_MODE_NONE = 0;
  19190. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19191. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19192. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19193. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19194. Camera._RIG_MODE_VR = 20;
  19195. Camera._RIG_MODE_WEBVR = 21;
  19196. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19197. Camera.UseAlternateWebVRRendering = false;
  19198. __decorate([
  19199. BABYLON.serializeAsVector3()
  19200. ], Camera.prototype, "position", void 0);
  19201. __decorate([
  19202. BABYLON.serializeAsVector3()
  19203. ], Camera.prototype, "upVector", void 0);
  19204. __decorate([
  19205. BABYLON.serialize()
  19206. ], Camera.prototype, "orthoLeft", void 0);
  19207. __decorate([
  19208. BABYLON.serialize()
  19209. ], Camera.prototype, "orthoRight", void 0);
  19210. __decorate([
  19211. BABYLON.serialize()
  19212. ], Camera.prototype, "orthoBottom", void 0);
  19213. __decorate([
  19214. BABYLON.serialize()
  19215. ], Camera.prototype, "orthoTop", void 0);
  19216. __decorate([
  19217. BABYLON.serialize()
  19218. ], Camera.prototype, "fov", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], Camera.prototype, "minZ", void 0);
  19222. __decorate([
  19223. BABYLON.serialize()
  19224. ], Camera.prototype, "maxZ", void 0);
  19225. __decorate([
  19226. BABYLON.serialize()
  19227. ], Camera.prototype, "inertia", void 0);
  19228. __decorate([
  19229. BABYLON.serialize()
  19230. ], Camera.prototype, "mode", void 0);
  19231. __decorate([
  19232. BABYLON.serialize()
  19233. ], Camera.prototype, "layerMask", void 0);
  19234. __decorate([
  19235. BABYLON.serialize()
  19236. ], Camera.prototype, "fovMode", void 0);
  19237. __decorate([
  19238. BABYLON.serialize()
  19239. ], Camera.prototype, "cameraRigMode", void 0);
  19240. __decorate([
  19241. BABYLON.serialize()
  19242. ], Camera.prototype, "interaxialDistance", void 0);
  19243. __decorate([
  19244. BABYLON.serialize()
  19245. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19246. return Camera;
  19247. }(BABYLON.Node));
  19248. BABYLON.Camera = Camera;
  19249. })(BABYLON || (BABYLON = {}));
  19250. //# sourceMappingURL=babylon.camera.js.map
  19251. var BABYLON;
  19252. (function (BABYLON) {
  19253. var RenderingManager = /** @class */ (function () {
  19254. function RenderingManager(scene) {
  19255. this._renderingGroups = new Array();
  19256. this._autoClearDepthStencil = {};
  19257. this._customOpaqueSortCompareFn = {};
  19258. this._customAlphaTestSortCompareFn = {};
  19259. this._customTransparentSortCompareFn = {};
  19260. this._renderinGroupInfo = null;
  19261. this._scene = scene;
  19262. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19263. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19264. }
  19265. }
  19266. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19267. if (depth === void 0) { depth = true; }
  19268. if (stencil === void 0) { stencil = true; }
  19269. if (this._depthStencilBufferAlreadyCleaned) {
  19270. return;
  19271. }
  19272. this._scene.getEngine().clear(null, false, depth, stencil);
  19273. this._depthStencilBufferAlreadyCleaned = true;
  19274. };
  19275. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19276. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19277. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19278. var info = null;
  19279. if (observable) {
  19280. if (!this._renderinGroupInfo) {
  19281. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19282. }
  19283. info = this._renderinGroupInfo;
  19284. info.scene = this._scene;
  19285. info.camera = this._scene.activeCamera;
  19286. }
  19287. // Dispatch sprites
  19288. if (renderSprites) {
  19289. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19290. var manager = this._scene.spriteManagers[index];
  19291. this.dispatchSprites(manager);
  19292. }
  19293. }
  19294. // Render
  19295. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19296. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19297. var renderingGroup = this._renderingGroups[index];
  19298. if (!renderingGroup && !observable)
  19299. continue;
  19300. var renderingGroupMask = 0;
  19301. // Fire PRECLEAR stage
  19302. if (observable && info) {
  19303. renderingGroupMask = Math.pow(2, index);
  19304. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19305. info.renderingGroupId = index;
  19306. observable.notifyObservers(info, renderingGroupMask);
  19307. }
  19308. // Clear depth/stencil if needed
  19309. if (RenderingManager.AUTOCLEAR) {
  19310. var autoClear = this._autoClearDepthStencil[index];
  19311. if (autoClear && autoClear.autoClear) {
  19312. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19313. }
  19314. }
  19315. if (observable && info) {
  19316. // Fire PREOPAQUE stage
  19317. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19318. observable.notifyObservers(info, renderingGroupMask);
  19319. // Fire PRETRANSPARENT stage
  19320. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19321. observable.notifyObservers(info, renderingGroupMask);
  19322. }
  19323. if (renderingGroup)
  19324. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19325. // Fire POSTTRANSPARENT stage
  19326. if (observable && info) {
  19327. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19328. observable.notifyObservers(info, renderingGroupMask);
  19329. }
  19330. }
  19331. };
  19332. RenderingManager.prototype.reset = function () {
  19333. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19334. var renderingGroup = this._renderingGroups[index];
  19335. if (renderingGroup) {
  19336. renderingGroup.prepare();
  19337. }
  19338. }
  19339. };
  19340. RenderingManager.prototype.dispose = function () {
  19341. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19342. var renderingGroup = this._renderingGroups[index];
  19343. if (renderingGroup) {
  19344. renderingGroup.dispose();
  19345. }
  19346. }
  19347. this._renderingGroups.length = 0;
  19348. };
  19349. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19350. if (this._renderingGroups[renderingGroupId] === undefined) {
  19351. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19352. }
  19353. };
  19354. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19355. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19356. this._prepareRenderingGroup(renderingGroupId);
  19357. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19358. };
  19359. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19360. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19361. this._prepareRenderingGroup(renderingGroupId);
  19362. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19363. };
  19364. /**
  19365. * @param subMesh The submesh to dispatch
  19366. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19367. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19368. */
  19369. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19370. if (mesh === undefined) {
  19371. mesh = subMesh.getMesh();
  19372. }
  19373. var renderingGroupId = mesh.renderingGroupId || 0;
  19374. this._prepareRenderingGroup(renderingGroupId);
  19375. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19376. };
  19377. /**
  19378. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19379. * This allowed control for front to back rendering or reversly depending of the special needs.
  19380. *
  19381. * @param renderingGroupId The rendering group id corresponding to its index
  19382. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19383. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19384. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19385. */
  19386. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19387. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19388. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19389. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19390. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19391. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19392. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19393. if (this._renderingGroups[renderingGroupId]) {
  19394. var group = this._renderingGroups[renderingGroupId];
  19395. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19396. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19397. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19398. }
  19399. };
  19400. /**
  19401. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19402. *
  19403. * @param renderingGroupId The rendering group id corresponding to its index
  19404. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19405. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19406. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19407. */
  19408. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19409. if (depth === void 0) { depth = true; }
  19410. if (stencil === void 0) { stencil = true; }
  19411. this._autoClearDepthStencil[renderingGroupId] = {
  19412. autoClear: autoClearDepthStencil,
  19413. depth: depth,
  19414. stencil: stencil
  19415. };
  19416. };
  19417. /**
  19418. * The max id used for rendering groups (not included)
  19419. */
  19420. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19421. /**
  19422. * The min id used for rendering groups (included)
  19423. */
  19424. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19425. /**
  19426. * Used to globally prevent autoclearing scenes.
  19427. */
  19428. RenderingManager.AUTOCLEAR = true;
  19429. return RenderingManager;
  19430. }());
  19431. BABYLON.RenderingManager = RenderingManager;
  19432. })(BABYLON || (BABYLON = {}));
  19433. //# sourceMappingURL=babylon.renderingManager.js.map
  19434. var BABYLON;
  19435. (function (BABYLON) {
  19436. var RenderingGroup = /** @class */ (function () {
  19437. /**
  19438. * Creates a new rendering group.
  19439. * @param index The rendering group index
  19440. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19441. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19442. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19443. */
  19444. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19445. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19446. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19447. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19448. this.index = index;
  19449. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19450. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19451. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19452. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19453. this._particleSystems = new BABYLON.SmartArray(256);
  19454. this._spriteManagers = new BABYLON.SmartArray(256);
  19455. this._edgesRenderers = new BABYLON.SmartArray(16);
  19456. this._scene = scene;
  19457. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19458. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19459. this.transparentSortCompareFn = transparentSortCompareFn;
  19460. }
  19461. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19462. /**
  19463. * Set the opaque sort comparison function.
  19464. * If null the sub meshes will be render in the order they were created
  19465. */
  19466. set: function (value) {
  19467. this._opaqueSortCompareFn = value;
  19468. if (value) {
  19469. this._renderOpaque = this.renderOpaqueSorted;
  19470. }
  19471. else {
  19472. this._renderOpaque = RenderingGroup.renderUnsorted;
  19473. }
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19479. /**
  19480. * Set the alpha test sort comparison function.
  19481. * If null the sub meshes will be render in the order they were created
  19482. */
  19483. set: function (value) {
  19484. this._alphaTestSortCompareFn = value;
  19485. if (value) {
  19486. this._renderAlphaTest = this.renderAlphaTestSorted;
  19487. }
  19488. else {
  19489. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19490. }
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19496. /**
  19497. * Set the transparent sort comparison function.
  19498. * If null the sub meshes will be render in the order they were created
  19499. */
  19500. set: function (value) {
  19501. if (value) {
  19502. this._transparentSortCompareFn = value;
  19503. }
  19504. else {
  19505. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19506. }
  19507. this._renderTransparent = this.renderTransparentSorted;
  19508. },
  19509. enumerable: true,
  19510. configurable: true
  19511. });
  19512. /**
  19513. * Render all the sub meshes contained in the group.
  19514. * @param customRenderFunction Used to override the default render behaviour of the group.
  19515. * @returns true if rendered some submeshes.
  19516. */
  19517. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19518. if (customRenderFunction) {
  19519. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19520. return;
  19521. }
  19522. var engine = this._scene.getEngine();
  19523. // Depth only
  19524. if (this._depthOnlySubMeshes.length !== 0) {
  19525. engine.setColorWrite(false);
  19526. this._renderAlphaTest(this._depthOnlySubMeshes);
  19527. engine.setColorWrite(true);
  19528. }
  19529. // Opaque
  19530. if (this._opaqueSubMeshes.length !== 0) {
  19531. this._renderOpaque(this._opaqueSubMeshes);
  19532. }
  19533. // Alpha test
  19534. if (this._alphaTestSubMeshes.length !== 0) {
  19535. this._renderAlphaTest(this._alphaTestSubMeshes);
  19536. }
  19537. var stencilState = engine.getStencilBuffer();
  19538. engine.setStencilBuffer(false);
  19539. // Sprites
  19540. if (renderSprites) {
  19541. this._renderSprites();
  19542. }
  19543. // Particles
  19544. if (renderParticles) {
  19545. this._renderParticles(activeMeshes);
  19546. }
  19547. if (this.onBeforeTransparentRendering) {
  19548. this.onBeforeTransparentRendering();
  19549. }
  19550. // Transparent
  19551. if (this._transparentSubMeshes.length !== 0) {
  19552. this._renderTransparent(this._transparentSubMeshes);
  19553. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19554. }
  19555. // Set back stencil to false in case it changes before the edge renderer.
  19556. engine.setStencilBuffer(false);
  19557. // Edges
  19558. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19559. this._edgesRenderers.data[edgesRendererIndex].render();
  19560. }
  19561. // Restore Stencil state.
  19562. engine.setStencilBuffer(stencilState);
  19563. };
  19564. /**
  19565. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19566. * @param subMeshes The submeshes to render
  19567. */
  19568. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19569. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19570. };
  19571. /**
  19572. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19573. * @param subMeshes The submeshes to render
  19574. */
  19575. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19576. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19577. };
  19578. /**
  19579. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19580. * @param subMeshes The submeshes to render
  19581. */
  19582. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19583. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19584. };
  19585. /**
  19586. * Renders the submeshes in a specified order.
  19587. * @param subMeshes The submeshes to sort before render
  19588. * @param sortCompareFn The comparison function use to sort
  19589. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19590. * @param transparent Specifies to activate blending if true
  19591. */
  19592. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19593. var subIndex = 0;
  19594. var subMesh;
  19595. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19596. for (; subIndex < subMeshes.length; subIndex++) {
  19597. subMesh = subMeshes.data[subIndex];
  19598. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19599. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19600. }
  19601. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19602. if (sortCompareFn) {
  19603. sortedArray.sort(sortCompareFn);
  19604. }
  19605. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19606. subMesh = sortedArray[subIndex];
  19607. if (transparent) {
  19608. var material = subMesh.getMaterial();
  19609. if (material && material.needDepthPrePass) {
  19610. var engine = material.getScene().getEngine();
  19611. engine.setColorWrite(false);
  19612. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19613. subMesh.render(false);
  19614. engine.setColorWrite(true);
  19615. }
  19616. }
  19617. subMesh.render(transparent);
  19618. }
  19619. };
  19620. /**
  19621. * Renders the submeshes in the order they were dispatched (no sort applied).
  19622. * @param subMeshes The submeshes to render
  19623. */
  19624. RenderingGroup.renderUnsorted = function (subMeshes) {
  19625. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19626. var submesh = subMeshes.data[subIndex];
  19627. submesh.render(false);
  19628. }
  19629. };
  19630. /**
  19631. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19632. * are rendered back to front if in the same alpha index.
  19633. *
  19634. * @param a The first submesh
  19635. * @param b The second submesh
  19636. * @returns The result of the comparison
  19637. */
  19638. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19639. // Alpha index first
  19640. if (a._alphaIndex > b._alphaIndex) {
  19641. return 1;
  19642. }
  19643. if (a._alphaIndex < b._alphaIndex) {
  19644. return -1;
  19645. }
  19646. // Then distance to camera
  19647. return RenderingGroup.backToFrontSortCompare(a, b);
  19648. };
  19649. /**
  19650. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19651. * are rendered back to front.
  19652. *
  19653. * @param a The first submesh
  19654. * @param b The second submesh
  19655. * @returns The result of the comparison
  19656. */
  19657. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19658. // Then distance to camera
  19659. if (a._distanceToCamera < b._distanceToCamera) {
  19660. return 1;
  19661. }
  19662. if (a._distanceToCamera > b._distanceToCamera) {
  19663. return -1;
  19664. }
  19665. return 0;
  19666. };
  19667. /**
  19668. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19669. * are rendered front to back (prevent overdraw).
  19670. *
  19671. * @param a The first submesh
  19672. * @param b The second submesh
  19673. * @returns The result of the comparison
  19674. */
  19675. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19676. // Then distance to camera
  19677. if (a._distanceToCamera < b._distanceToCamera) {
  19678. return -1;
  19679. }
  19680. if (a._distanceToCamera > b._distanceToCamera) {
  19681. return 1;
  19682. }
  19683. return 0;
  19684. };
  19685. /**
  19686. * Resets the different lists of submeshes to prepare a new frame.
  19687. */
  19688. RenderingGroup.prototype.prepare = function () {
  19689. this._opaqueSubMeshes.reset();
  19690. this._transparentSubMeshes.reset();
  19691. this._alphaTestSubMeshes.reset();
  19692. this._depthOnlySubMeshes.reset();
  19693. this._particleSystems.reset();
  19694. this._spriteManagers.reset();
  19695. this._edgesRenderers.reset();
  19696. };
  19697. RenderingGroup.prototype.dispose = function () {
  19698. this._opaqueSubMeshes.dispose();
  19699. this._transparentSubMeshes.dispose();
  19700. this._alphaTestSubMeshes.dispose();
  19701. this._depthOnlySubMeshes.dispose();
  19702. this._particleSystems.dispose();
  19703. this._spriteManagers.dispose();
  19704. this._edgesRenderers.dispose();
  19705. };
  19706. /**
  19707. * Inserts the submesh in its correct queue depending on its material.
  19708. * @param subMesh The submesh to dispatch
  19709. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19710. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19711. */
  19712. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19713. // Get mesh and materials if not provided
  19714. if (mesh === undefined) {
  19715. mesh = subMesh.getMesh();
  19716. }
  19717. if (material === undefined) {
  19718. material = subMesh.getMaterial();
  19719. }
  19720. if (material === null || material === undefined) {
  19721. return;
  19722. }
  19723. if (material.needAlphaBlendingForMesh(mesh)) {
  19724. this._transparentSubMeshes.push(subMesh);
  19725. }
  19726. else if (material.needAlphaTesting()) {
  19727. if (material.needDepthPrePass) {
  19728. this._depthOnlySubMeshes.push(subMesh);
  19729. }
  19730. this._alphaTestSubMeshes.push(subMesh);
  19731. }
  19732. else {
  19733. if (material.needDepthPrePass) {
  19734. this._depthOnlySubMeshes.push(subMesh);
  19735. }
  19736. this._opaqueSubMeshes.push(subMesh); // Opaque
  19737. }
  19738. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19739. this._edgesRenderers.push(mesh._edgesRenderer);
  19740. }
  19741. };
  19742. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19743. this._spriteManagers.push(spriteManager);
  19744. };
  19745. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19746. this._particleSystems.push(particleSystem);
  19747. };
  19748. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19749. if (this._particleSystems.length === 0) {
  19750. return;
  19751. }
  19752. // Particles
  19753. var activeCamera = this._scene.activeCamera;
  19754. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19755. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19756. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19757. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19758. continue;
  19759. }
  19760. var emitter = particleSystem.emitter;
  19761. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19762. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19763. }
  19764. }
  19765. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19766. };
  19767. RenderingGroup.prototype._renderSprites = function () {
  19768. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19769. return;
  19770. }
  19771. // Sprites
  19772. var activeCamera = this._scene.activeCamera;
  19773. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19774. for (var id = 0; id < this._spriteManagers.length; id++) {
  19775. var spriteManager = this._spriteManagers.data[id];
  19776. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19777. spriteManager.render();
  19778. }
  19779. }
  19780. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19781. };
  19782. return RenderingGroup;
  19783. }());
  19784. BABYLON.RenderingGroup = RenderingGroup;
  19785. })(BABYLON || (BABYLON = {}));
  19786. //# sourceMappingURL=babylon.renderingGroup.js.map
  19787. var BABYLON;
  19788. (function (BABYLON) {
  19789. var ClickInfo = /** @class */ (function () {
  19790. function ClickInfo() {
  19791. this._singleClick = false;
  19792. this._doubleClick = false;
  19793. this._hasSwiped = false;
  19794. this._ignore = false;
  19795. }
  19796. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19797. get: function () {
  19798. return this._singleClick;
  19799. },
  19800. set: function (b) {
  19801. this._singleClick = b;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19807. get: function () {
  19808. return this._doubleClick;
  19809. },
  19810. set: function (b) {
  19811. this._doubleClick = b;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19817. get: function () {
  19818. return this._hasSwiped;
  19819. },
  19820. set: function (b) {
  19821. this._hasSwiped = b;
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19827. get: function () {
  19828. return this._ignore;
  19829. },
  19830. set: function (b) {
  19831. this._ignore = b;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. return ClickInfo;
  19837. }());
  19838. /**
  19839. * This class is used by the onRenderingGroupObservable
  19840. */
  19841. var RenderingGroupInfo = /** @class */ (function () {
  19842. function RenderingGroupInfo() {
  19843. }
  19844. /**
  19845. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19846. * This stage will be fired no matter what
  19847. */
  19848. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19849. /**
  19850. * Called before opaque object are rendered.
  19851. * This stage will be fired only if there's 3D Opaque content to render
  19852. */
  19853. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19854. /**
  19855. * Called after the opaque objects are rendered and before the transparent ones
  19856. * This stage will be fired only if there's 3D transparent content to render
  19857. */
  19858. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19859. /**
  19860. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19861. * This stage will be fired no matter what
  19862. */
  19863. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19864. return RenderingGroupInfo;
  19865. }());
  19866. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19867. /**
  19868. * Represents a scene to be rendered by the engine.
  19869. * @see http://doc.babylonjs.com/page.php?p=21911
  19870. */
  19871. var Scene = /** @class */ (function () {
  19872. /**
  19873. * @constructor
  19874. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19875. */
  19876. function Scene(engine) {
  19877. // Members
  19878. this.autoClear = true;
  19879. this.autoClearDepthAndStencil = true;
  19880. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19881. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19882. this.forceWireframe = false;
  19883. this._forcePointsCloud = false;
  19884. this.forceShowBoundingBoxes = false;
  19885. this.animationsEnabled = true;
  19886. this.useConstantAnimationDeltaTime = false;
  19887. this.constantlyUpdateMeshUnderPointer = false;
  19888. this.hoverCursor = "pointer";
  19889. this.defaultCursor = "";
  19890. /**
  19891. * This is used to call preventDefault() on pointer down
  19892. * in order to block unwanted artifacts like system double clicks
  19893. */
  19894. this.preventDefaultOnPointerDown = true;
  19895. // Metadata
  19896. this.metadata = null;
  19897. /**
  19898. * An event triggered when the scene is disposed.
  19899. * @type {BABYLON.Observable}
  19900. */
  19901. this.onDisposeObservable = new BABYLON.Observable();
  19902. /**
  19903. * An event triggered before rendering the scene (right after animations and physics)
  19904. * @type {BABYLON.Observable}
  19905. */
  19906. this.onBeforeRenderObservable = new BABYLON.Observable();
  19907. /**
  19908. * An event triggered after rendering the scene
  19909. * @type {BABYLON.Observable}
  19910. */
  19911. this.onAfterRenderObservable = new BABYLON.Observable();
  19912. /**
  19913. * An event triggered before animating the scene
  19914. * @type {BABYLON.Observable}
  19915. */
  19916. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19917. /**
  19918. * An event triggered after animations processing
  19919. * @type {BABYLON.Observable}
  19920. */
  19921. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19922. /**
  19923. * An event triggered before draw calls are ready to be sent
  19924. * @type {BABYLON.Observable}
  19925. */
  19926. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19927. /**
  19928. * An event triggered after draw calls have been sent
  19929. * @type {BABYLON.Observable}
  19930. */
  19931. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19932. /**
  19933. * An event triggered when physic simulation is about to be run
  19934. * @type {BABYLON.Observable}
  19935. */
  19936. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19937. /**
  19938. * An event triggered when physic simulation has been done
  19939. * @type {BABYLON.Observable}
  19940. */
  19941. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19942. /**
  19943. * An event triggered when the scene is ready
  19944. * @type {BABYLON.Observable}
  19945. */
  19946. this.onReadyObservable = new BABYLON.Observable();
  19947. /**
  19948. * An event triggered before rendering a camera
  19949. * @type {BABYLON.Observable}
  19950. */
  19951. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19952. /**
  19953. * An event triggered after rendering a camera
  19954. * @type {BABYLON.Observable}
  19955. */
  19956. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19957. /**
  19958. * An event triggered when active meshes evaluation is about to start
  19959. * @type {BABYLON.Observable}
  19960. */
  19961. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19962. /**
  19963. * An event triggered when active meshes evaluation is done
  19964. * @type {BABYLON.Observable}
  19965. */
  19966. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19967. /**
  19968. * An event triggered when particles rendering is about to start
  19969. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19970. * @type {BABYLON.Observable}
  19971. */
  19972. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19973. /**
  19974. * An event triggered when particles rendering is done
  19975. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19976. * @type {BABYLON.Observable}
  19977. */
  19978. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19979. /**
  19980. * An event triggered when sprites rendering is about to start
  19981. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19982. * @type {BABYLON.Observable}
  19983. */
  19984. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19985. /**
  19986. * An event triggered when sprites rendering is done
  19987. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19988. * @type {BABYLON.Observable}
  19989. */
  19990. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19991. /**
  19992. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19993. * @type {BABYLON.Observable}
  19994. */
  19995. this.onDataLoadedObservable = new BABYLON.Observable();
  19996. /**
  19997. * An event triggered when a camera is created
  19998. * @type {BABYLON.Observable}
  19999. */
  20000. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20001. /**
  20002. * An event triggered when a camera is removed
  20003. * @type {BABYLON.Observable}
  20004. */
  20005. this.onCameraRemovedObservable = new BABYLON.Observable();
  20006. /**
  20007. * An event triggered when a light is created
  20008. * @type {BABYLON.Observable}
  20009. */
  20010. this.onNewLightAddedObservable = new BABYLON.Observable();
  20011. /**
  20012. * An event triggered when a light is removed
  20013. * @type {BABYLON.Observable}
  20014. */
  20015. this.onLightRemovedObservable = new BABYLON.Observable();
  20016. /**
  20017. * An event triggered when a geometry is created
  20018. * @type {BABYLON.Observable}
  20019. */
  20020. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20021. /**
  20022. * An event triggered when a geometry is removed
  20023. * @type {BABYLON.Observable}
  20024. */
  20025. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20026. /**
  20027. * An event triggered when a transform node is created
  20028. * @type {BABYLON.Observable}
  20029. */
  20030. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20031. /**
  20032. * An event triggered when a transform node is removed
  20033. * @type {BABYLON.Observable}
  20034. */
  20035. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20036. /**
  20037. * An event triggered when a mesh is created
  20038. * @type {BABYLON.Observable}
  20039. */
  20040. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20041. /**
  20042. * An event triggered when a mesh is removed
  20043. * @type {BABYLON.Observable}
  20044. */
  20045. this.onMeshRemovedObservable = new BABYLON.Observable();
  20046. /**
  20047. * An event triggered when render targets are about to be rendered
  20048. * Can happen multiple times per frame.
  20049. * @type {BABYLON.Observable}
  20050. */
  20051. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20052. /**
  20053. * An event triggered when render targets were rendered.
  20054. * Can happen multiple times per frame.
  20055. * @type {BABYLON.Observable}
  20056. */
  20057. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20058. /**
  20059. * An event triggered before calculating deterministic simulation step
  20060. * @type {BABYLON.Observable}
  20061. */
  20062. this.onBeforeStepObservable = new BABYLON.Observable();
  20063. /**
  20064. * An event triggered after calculating deterministic simulation step
  20065. * @type {BABYLON.Observable}
  20066. */
  20067. this.onAfterStepObservable = new BABYLON.Observable();
  20068. /**
  20069. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20070. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20071. * 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)
  20072. */
  20073. this.onRenderingGroupObservable = new BABYLON.Observable();
  20074. // Animations
  20075. this.animations = [];
  20076. /**
  20077. * 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).
  20078. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20079. */
  20080. this.onPrePointerObservable = new BABYLON.Observable();
  20081. /**
  20082. * Observable event triggered each time an input event is received from the rendering canvas
  20083. */
  20084. this.onPointerObservable = new BABYLON.Observable();
  20085. this._meshPickProceed = false;
  20086. this._currentPickResult = null;
  20087. this._previousPickResult = null;
  20088. this._totalPointersPressed = 0;
  20089. this._doubleClickOccured = false;
  20090. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20091. this.cameraToUseForPointers = null;
  20092. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20093. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20094. this._startingPointerTime = 0;
  20095. this._previousStartingPointerTime = 0;
  20096. // Deterministic lockstep
  20097. this._timeAccumulator = 0;
  20098. this._currentStepId = 0;
  20099. this._currentInternalStep = 0;
  20100. // Keyboard
  20101. /**
  20102. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20103. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20104. */
  20105. this.onPreKeyboardObservable = new BABYLON.Observable();
  20106. /**
  20107. * Observable event triggered each time an keyboard event is received from the hosting window
  20108. */
  20109. this.onKeyboardObservable = new BABYLON.Observable();
  20110. // Coordinate system
  20111. /**
  20112. * use right-handed coordinate system on this scene.
  20113. * @type {boolean}
  20114. */
  20115. this._useRightHandedSystem = false;
  20116. // Fog
  20117. this._fogEnabled = true;
  20118. this._fogMode = Scene.FOGMODE_NONE;
  20119. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20120. this.fogDensity = 0.1;
  20121. this.fogStart = 0;
  20122. this.fogEnd = 1000.0;
  20123. // Lights
  20124. /**
  20125. * is shadow enabled on this scene.
  20126. * @type {boolean}
  20127. */
  20128. this._shadowsEnabled = true;
  20129. /**
  20130. * is light enabled on this scene.
  20131. * @type {boolean}
  20132. */
  20133. this._lightsEnabled = true;
  20134. /**
  20135. * All of the lights added to this scene.
  20136. * @see BABYLON.Light
  20137. * @type {BABYLON.Light[]}
  20138. */
  20139. this.lights = new Array();
  20140. // Cameras
  20141. /** All of the cameras added to this scene. */
  20142. this.cameras = new Array();
  20143. /** All of the active cameras added to this scene. */
  20144. this.activeCameras = new Array();
  20145. // Meshes
  20146. /**
  20147. * All of the tranform nodes added to this scene.
  20148. * @see BABYLON.TransformNode
  20149. * @type {BABYLON.TransformNode[]}
  20150. */
  20151. this.transformNodes = new Array();
  20152. /**
  20153. * All of the (abstract) meshes added to this scene.
  20154. * @see BABYLON.AbstractMesh
  20155. * @type {BABYLON.AbstractMesh[]}
  20156. */
  20157. this.meshes = new Array();
  20158. /**
  20159. * All of the animation groups added to this scene.
  20160. * @see BABYLON.AnimationGroup
  20161. * @type {BABYLON.AnimationGroup[]}
  20162. */
  20163. this.animationGroups = new Array();
  20164. // Geometries
  20165. this._geometries = new Array();
  20166. this.materials = new Array();
  20167. this.multiMaterials = new Array();
  20168. // Textures
  20169. this._texturesEnabled = true;
  20170. this.textures = new Array();
  20171. // Particles
  20172. this.particlesEnabled = true;
  20173. this.particleSystems = new Array();
  20174. // Sprites
  20175. this.spritesEnabled = true;
  20176. this.spriteManagers = new Array();
  20177. // Layers
  20178. this.layers = new Array();
  20179. this.highlightLayers = new Array();
  20180. // Skeletons
  20181. this._skeletonsEnabled = true;
  20182. this.skeletons = new Array();
  20183. // Morph targets
  20184. this.morphTargetManagers = new Array();
  20185. // Lens flares
  20186. this.lensFlaresEnabled = true;
  20187. this.lensFlareSystems = new Array();
  20188. // Collisions
  20189. this.collisionsEnabled = true;
  20190. /** Defines the gravity applied to this scene */
  20191. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20192. // Postprocesses
  20193. this.postProcesses = new Array();
  20194. this.postProcessesEnabled = true;
  20195. // Customs render targets
  20196. this.renderTargetsEnabled = true;
  20197. this.dumpNextRenderTargets = false;
  20198. this.customRenderTargets = new Array();
  20199. // Imported meshes
  20200. this.importedMeshesFiles = new Array();
  20201. // Probes
  20202. this.probesEnabled = true;
  20203. this.reflectionProbes = new Array();
  20204. this._actionManagers = new Array();
  20205. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20206. // Procedural textures
  20207. this.proceduralTexturesEnabled = true;
  20208. this._proceduralTextures = new Array();
  20209. this.soundTracks = new Array();
  20210. this._audioEnabled = true;
  20211. this._headphone = false;
  20212. // Performance counters
  20213. this._totalVertices = new BABYLON.PerfCounter();
  20214. this._activeIndices = new BABYLON.PerfCounter();
  20215. this._activeParticles = new BABYLON.PerfCounter();
  20216. this._activeBones = new BABYLON.PerfCounter();
  20217. this._animationTime = 0;
  20218. this.animationTimeScale = 1;
  20219. this._renderId = 0;
  20220. this._executeWhenReadyTimeoutId = -1;
  20221. this._intermediateRendering = false;
  20222. this._viewUpdateFlag = -1;
  20223. this._projectionUpdateFlag = -1;
  20224. this._alternateViewUpdateFlag = -1;
  20225. this._alternateProjectionUpdateFlag = -1;
  20226. this._toBeDisposed = new BABYLON.SmartArray(256);
  20227. this._activeRequests = new Array();
  20228. this._pendingData = new Array();
  20229. this._isDisposed = false;
  20230. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20231. this._activeMeshes = new BABYLON.SmartArray(256);
  20232. this._processedMaterials = new BABYLON.SmartArray(256);
  20233. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20234. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20235. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20236. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20237. this._activeAnimatables = new Array();
  20238. this._transformMatrix = BABYLON.Matrix.Zero();
  20239. this._useAlternateCameraConfiguration = false;
  20240. this._alternateRendering = false;
  20241. this.requireLightSorting = false;
  20242. this._activeMeshesFrozen = false;
  20243. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20244. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20245. this._engine.scenes.push(this);
  20246. this._uid = null;
  20247. this._renderingManager = new BABYLON.RenderingManager(this);
  20248. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20249. if (BABYLON.OutlineRenderer) {
  20250. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20251. }
  20252. if (BABYLON.Tools.IsWindowObjectExist()) {
  20253. this.attachControl();
  20254. }
  20255. //simplification queue
  20256. if (BABYLON.SimplificationQueue) {
  20257. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20258. }
  20259. //collision coordinator initialization. For now legacy per default.
  20260. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20261. // Uniform Buffer
  20262. this._createUbo();
  20263. // Default Image processing definition.
  20264. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20265. }
  20266. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20267. /** The fog is deactivated */
  20268. get: function () {
  20269. return Scene._FOGMODE_NONE;
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20275. /** The fog density is following an exponential function */
  20276. get: function () {
  20277. return Scene._FOGMODE_EXP;
  20278. },
  20279. enumerable: true,
  20280. configurable: true
  20281. });
  20282. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20283. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20284. get: function () {
  20285. return Scene._FOGMODE_EXP2;
  20286. },
  20287. enumerable: true,
  20288. configurable: true
  20289. });
  20290. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20291. /** The fog density is following a linear function. */
  20292. get: function () {
  20293. return Scene._FOGMODE_LINEAR;
  20294. },
  20295. enumerable: true,
  20296. configurable: true
  20297. });
  20298. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20299. /**
  20300. * Texture used in all pbr material as the reflection texture.
  20301. * As in the majority of the scene they are the same (exception for multi room and so on),
  20302. * this is easier to reference from here than from all the materials.
  20303. */
  20304. get: function () {
  20305. return this._environmentTexture;
  20306. },
  20307. /**
  20308. * Texture used in all pbr material as the reflection texture.
  20309. * As in the majority of the scene they are the same (exception for multi room and so on),
  20310. * this is easier to set here than in all the materials.
  20311. */
  20312. set: function (value) {
  20313. if (this._environmentTexture === value) {
  20314. return;
  20315. }
  20316. this._environmentTexture = value;
  20317. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20323. /**
  20324. * Default image processing configuration used either in the rendering
  20325. * Forward main pass or through the imageProcessingPostProcess if present.
  20326. * As in the majority of the scene they are the same (exception for multi camera),
  20327. * this is easier to reference from here than from all the materials and post process.
  20328. *
  20329. * No setter as we it is a shared configuration, you can set the values instead.
  20330. */
  20331. get: function () {
  20332. return this._imageProcessingConfiguration;
  20333. },
  20334. enumerable: true,
  20335. configurable: true
  20336. });
  20337. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20338. get: function () {
  20339. return this._forcePointsCloud;
  20340. },
  20341. set: function (value) {
  20342. if (this._forcePointsCloud === value) {
  20343. return;
  20344. }
  20345. this._forcePointsCloud = value;
  20346. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20347. },
  20348. enumerable: true,
  20349. configurable: true
  20350. });
  20351. Object.defineProperty(Scene.prototype, "onDispose", {
  20352. /** A function to be executed when this scene is disposed. */
  20353. set: function (callback) {
  20354. if (this._onDisposeObserver) {
  20355. this.onDisposeObservable.remove(this._onDisposeObserver);
  20356. }
  20357. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20358. },
  20359. enumerable: true,
  20360. configurable: true
  20361. });
  20362. Object.defineProperty(Scene.prototype, "beforeRender", {
  20363. /** A function to be executed before rendering this scene */
  20364. set: function (callback) {
  20365. if (this._onBeforeRenderObserver) {
  20366. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20367. }
  20368. if (callback) {
  20369. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20370. }
  20371. },
  20372. enumerable: true,
  20373. configurable: true
  20374. });
  20375. Object.defineProperty(Scene.prototype, "afterRender", {
  20376. /** A function to be executed after rendering this scene */
  20377. set: function (callback) {
  20378. if (this._onAfterRenderObserver) {
  20379. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20380. }
  20381. if (callback) {
  20382. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20383. }
  20384. },
  20385. enumerable: true,
  20386. configurable: true
  20387. });
  20388. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20389. set: function (callback) {
  20390. if (this._onBeforeCameraRenderObserver) {
  20391. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20392. }
  20393. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20394. },
  20395. enumerable: true,
  20396. configurable: true
  20397. });
  20398. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20399. set: function (callback) {
  20400. if (this._onAfterCameraRenderObserver) {
  20401. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20402. }
  20403. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20404. },
  20405. enumerable: true,
  20406. configurable: true
  20407. });
  20408. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20409. get: function () {
  20410. if (!this._gamepadManager) {
  20411. this._gamepadManager = new BABYLON.GamepadManager(this);
  20412. }
  20413. return this._gamepadManager;
  20414. },
  20415. enumerable: true,
  20416. configurable: true
  20417. });
  20418. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20419. get: function () {
  20420. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20421. },
  20422. enumerable: true,
  20423. configurable: true
  20424. });
  20425. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20426. get: function () {
  20427. return this._useRightHandedSystem;
  20428. },
  20429. set: function (value) {
  20430. if (this._useRightHandedSystem === value) {
  20431. return;
  20432. }
  20433. this._useRightHandedSystem = value;
  20434. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20435. },
  20436. enumerable: true,
  20437. configurable: true
  20438. });
  20439. Scene.prototype.setStepId = function (newStepId) {
  20440. this._currentStepId = newStepId;
  20441. };
  20442. ;
  20443. Scene.prototype.getStepId = function () {
  20444. return this._currentStepId;
  20445. };
  20446. ;
  20447. Scene.prototype.getInternalStep = function () {
  20448. return this._currentInternalStep;
  20449. };
  20450. ;
  20451. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20452. get: function () {
  20453. return this._fogEnabled;
  20454. },
  20455. /**
  20456. * is fog enabled on this scene.
  20457. */
  20458. set: function (value) {
  20459. if (this._fogEnabled === value) {
  20460. return;
  20461. }
  20462. this._fogEnabled = value;
  20463. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20464. },
  20465. enumerable: true,
  20466. configurable: true
  20467. });
  20468. Object.defineProperty(Scene.prototype, "fogMode", {
  20469. get: function () {
  20470. return this._fogMode;
  20471. },
  20472. set: function (value) {
  20473. if (this._fogMode === value) {
  20474. return;
  20475. }
  20476. this._fogMode = value;
  20477. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20478. },
  20479. enumerable: true,
  20480. configurable: true
  20481. });
  20482. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20483. get: function () {
  20484. return this._shadowsEnabled;
  20485. },
  20486. set: function (value) {
  20487. if (this._shadowsEnabled === value) {
  20488. return;
  20489. }
  20490. this._shadowsEnabled = value;
  20491. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20492. },
  20493. enumerable: true,
  20494. configurable: true
  20495. });
  20496. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20497. get: function () {
  20498. return this._lightsEnabled;
  20499. },
  20500. set: function (value) {
  20501. if (this._lightsEnabled === value) {
  20502. return;
  20503. }
  20504. this._lightsEnabled = value;
  20505. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20506. },
  20507. enumerable: true,
  20508. configurable: true
  20509. });
  20510. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20511. /** The default material used on meshes when no material is affected */
  20512. get: function () {
  20513. if (!this._defaultMaterial) {
  20514. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20515. }
  20516. return this._defaultMaterial;
  20517. },
  20518. /** The default material used on meshes when no material is affected */
  20519. set: function (value) {
  20520. this._defaultMaterial = value;
  20521. },
  20522. enumerable: true,
  20523. configurable: true
  20524. });
  20525. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20526. get: function () {
  20527. return this._texturesEnabled;
  20528. },
  20529. set: function (value) {
  20530. if (this._texturesEnabled === value) {
  20531. return;
  20532. }
  20533. this._texturesEnabled = value;
  20534. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20540. get: function () {
  20541. return this._skeletonsEnabled;
  20542. },
  20543. set: function (value) {
  20544. if (this._skeletonsEnabled === value) {
  20545. return;
  20546. }
  20547. this._skeletonsEnabled = value;
  20548. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20549. },
  20550. enumerable: true,
  20551. configurable: true
  20552. });
  20553. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20554. get: function () {
  20555. if (!this._postProcessRenderPipelineManager) {
  20556. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20557. }
  20558. return this._postProcessRenderPipelineManager;
  20559. },
  20560. enumerable: true,
  20561. configurable: true
  20562. });
  20563. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20564. get: function () {
  20565. if (!this._mainSoundTrack) {
  20566. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20567. }
  20568. return this._mainSoundTrack;
  20569. },
  20570. enumerable: true,
  20571. configurable: true
  20572. });
  20573. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20574. get: function () {
  20575. return this._alternateRendering;
  20576. },
  20577. enumerable: true,
  20578. configurable: true
  20579. });
  20580. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20581. get: function () {
  20582. return this._frustumPlanes;
  20583. },
  20584. enumerable: true,
  20585. configurable: true
  20586. });
  20587. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20588. /**
  20589. * Gets the current geometry buffer associated to the scene.
  20590. */
  20591. get: function () {
  20592. return this._geometryBufferRenderer;
  20593. },
  20594. /**
  20595. * Sets the current geometry buffer for the scene.
  20596. */
  20597. set: function (geometryBufferRenderer) {
  20598. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20599. this._geometryBufferRenderer = geometryBufferRenderer;
  20600. }
  20601. },
  20602. enumerable: true,
  20603. configurable: true
  20604. });
  20605. Object.defineProperty(Scene.prototype, "debugLayer", {
  20606. // Properties
  20607. get: function () {
  20608. if (!this._debugLayer) {
  20609. this._debugLayer = new BABYLON.DebugLayer(this);
  20610. }
  20611. return this._debugLayer;
  20612. },
  20613. enumerable: true,
  20614. configurable: true
  20615. });
  20616. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20617. get: function () {
  20618. return this._workerCollisions;
  20619. },
  20620. set: function (enabled) {
  20621. if (!BABYLON.CollisionCoordinatorLegacy) {
  20622. return;
  20623. }
  20624. enabled = (enabled && !!Worker);
  20625. this._workerCollisions = enabled;
  20626. if (this.collisionCoordinator) {
  20627. this.collisionCoordinator.destroy();
  20628. }
  20629. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20630. this.collisionCoordinator.init(this);
  20631. },
  20632. enumerable: true,
  20633. configurable: true
  20634. });
  20635. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20636. get: function () {
  20637. return this._selectionOctree;
  20638. },
  20639. enumerable: true,
  20640. configurable: true
  20641. });
  20642. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20643. /**
  20644. * The mesh that is currently under the pointer.
  20645. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20646. */
  20647. get: function () {
  20648. return this._pointerOverMesh;
  20649. },
  20650. enumerable: true,
  20651. configurable: true
  20652. });
  20653. Object.defineProperty(Scene.prototype, "pointerX", {
  20654. /**
  20655. * Current on-screen X position of the pointer
  20656. * @return {number} X position of the pointer
  20657. */
  20658. get: function () {
  20659. return this._pointerX;
  20660. },
  20661. enumerable: true,
  20662. configurable: true
  20663. });
  20664. Object.defineProperty(Scene.prototype, "pointerY", {
  20665. /**
  20666. * Current on-screen Y position of the pointer
  20667. * @return {number} Y position of the pointer
  20668. */
  20669. get: function () {
  20670. return this._pointerY;
  20671. },
  20672. enumerable: true,
  20673. configurable: true
  20674. });
  20675. Scene.prototype.getCachedMaterial = function () {
  20676. return this._cachedMaterial;
  20677. };
  20678. Scene.prototype.getCachedEffect = function () {
  20679. return this._cachedEffect;
  20680. };
  20681. Scene.prototype.getCachedVisibility = function () {
  20682. return this._cachedVisibility;
  20683. };
  20684. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20685. if (visibility === void 0) { visibility = 1; }
  20686. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20687. };
  20688. Scene.prototype.getBoundingBoxRenderer = function () {
  20689. if (!this._boundingBoxRenderer) {
  20690. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20691. }
  20692. return this._boundingBoxRenderer;
  20693. };
  20694. Scene.prototype.getOutlineRenderer = function () {
  20695. return this._outlineRenderer;
  20696. };
  20697. Scene.prototype.getEngine = function () {
  20698. return this._engine;
  20699. };
  20700. Scene.prototype.getTotalVertices = function () {
  20701. return this._totalVertices.current;
  20702. };
  20703. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20704. get: function () {
  20705. return this._totalVertices;
  20706. },
  20707. enumerable: true,
  20708. configurable: true
  20709. });
  20710. Scene.prototype.getActiveIndices = function () {
  20711. return this._activeIndices.current;
  20712. };
  20713. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20714. get: function () {
  20715. return this._activeIndices;
  20716. },
  20717. enumerable: true,
  20718. configurable: true
  20719. });
  20720. Scene.prototype.getActiveParticles = function () {
  20721. return this._activeParticles.current;
  20722. };
  20723. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20724. get: function () {
  20725. return this._activeParticles;
  20726. },
  20727. enumerable: true,
  20728. configurable: true
  20729. });
  20730. Scene.prototype.getActiveBones = function () {
  20731. return this._activeBones.current;
  20732. };
  20733. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20734. get: function () {
  20735. return this._activeBones;
  20736. },
  20737. enumerable: true,
  20738. configurable: true
  20739. });
  20740. // Stats
  20741. Scene.prototype.getInterFramePerfCounter = function () {
  20742. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20743. return 0;
  20744. };
  20745. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20746. get: function () {
  20747. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20748. return null;
  20749. },
  20750. enumerable: true,
  20751. configurable: true
  20752. });
  20753. Scene.prototype.getLastFrameDuration = function () {
  20754. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20755. return 0;
  20756. };
  20757. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20758. get: function () {
  20759. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20760. return null;
  20761. },
  20762. enumerable: true,
  20763. configurable: true
  20764. });
  20765. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20766. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20767. return 0;
  20768. };
  20769. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20770. get: function () {
  20771. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20772. return null;
  20773. },
  20774. enumerable: true,
  20775. configurable: true
  20776. });
  20777. Scene.prototype.getActiveMeshes = function () {
  20778. return this._activeMeshes;
  20779. };
  20780. Scene.prototype.getRenderTargetsDuration = function () {
  20781. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20782. return 0;
  20783. };
  20784. Scene.prototype.getRenderDuration = function () {
  20785. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20786. return 0;
  20787. };
  20788. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20789. get: function () {
  20790. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20791. return null;
  20792. },
  20793. enumerable: true,
  20794. configurable: true
  20795. });
  20796. Scene.prototype.getParticlesDuration = function () {
  20797. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20798. return 0;
  20799. };
  20800. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20801. get: function () {
  20802. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20803. return null;
  20804. },
  20805. enumerable: true,
  20806. configurable: true
  20807. });
  20808. Scene.prototype.getSpritesDuration = function () {
  20809. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20810. return 0;
  20811. };
  20812. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20813. get: function () {
  20814. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20815. return null;
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. Scene.prototype.getAnimationRatio = function () {
  20821. return this._animationRatio;
  20822. };
  20823. Scene.prototype.getRenderId = function () {
  20824. return this._renderId;
  20825. };
  20826. Scene.prototype.incrementRenderId = function () {
  20827. this._renderId++;
  20828. };
  20829. Scene.prototype._updatePointerPosition = function (evt) {
  20830. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20831. if (!canvasRect) {
  20832. return;
  20833. }
  20834. this._pointerX = evt.clientX - canvasRect.left;
  20835. this._pointerY = evt.clientY - canvasRect.top;
  20836. this._unTranslatedPointerX = this._pointerX;
  20837. this._unTranslatedPointerY = this._pointerY;
  20838. };
  20839. Scene.prototype._createUbo = function () {
  20840. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20841. this._sceneUbo.addUniform("viewProjection", 16);
  20842. this._sceneUbo.addUniform("view", 16);
  20843. };
  20844. Scene.prototype._createAlternateUbo = function () {
  20845. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20846. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20847. this._alternateSceneUbo.addUniform("view", 16);
  20848. };
  20849. // Pointers handling
  20850. /**
  20851. * Use this method to simulate a pointer move on a mesh
  20852. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20853. */
  20854. Scene.prototype.simulatePointerMove = function (pickResult) {
  20855. var evt = new PointerEvent("pointermove");
  20856. return this._processPointerMove(pickResult, evt);
  20857. };
  20858. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20859. var canvas = this._engine.getRenderingCanvas();
  20860. if (!canvas) {
  20861. return this;
  20862. }
  20863. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20864. this.setPointerOverSprite(null);
  20865. this.setPointerOverMesh(pickResult.pickedMesh);
  20866. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20867. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20868. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20869. }
  20870. else {
  20871. canvas.style.cursor = this.hoverCursor;
  20872. }
  20873. }
  20874. else {
  20875. canvas.style.cursor = this.defaultCursor;
  20876. }
  20877. }
  20878. else {
  20879. this.setPointerOverMesh(null);
  20880. // Sprites
  20881. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20882. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20883. this.setPointerOverSprite(pickResult.pickedSprite);
  20884. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20885. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20886. }
  20887. else {
  20888. canvas.style.cursor = this.hoverCursor;
  20889. }
  20890. }
  20891. else {
  20892. this.setPointerOverSprite(null);
  20893. // Restore pointer
  20894. canvas.style.cursor = this.defaultCursor;
  20895. }
  20896. }
  20897. if (pickResult) {
  20898. if (this.onPointerMove) {
  20899. this.onPointerMove(evt, pickResult);
  20900. }
  20901. if (this.onPointerObservable.hasObservers()) {
  20902. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20903. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20904. this.onPointerObservable.notifyObservers(pi, type);
  20905. }
  20906. }
  20907. return this;
  20908. };
  20909. /**
  20910. * Use this method to simulate a pointer down on a mesh
  20911. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20912. */
  20913. Scene.prototype.simulatePointerDown = function (pickResult) {
  20914. var evt = new PointerEvent("pointerdown");
  20915. return this._processPointerDown(pickResult, evt);
  20916. };
  20917. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20918. var _this = this;
  20919. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20920. this._pickedDownMesh = pickResult.pickedMesh;
  20921. var actionManager = pickResult.pickedMesh.actionManager;
  20922. if (actionManager) {
  20923. if (actionManager.hasPickTriggers) {
  20924. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20925. switch (evt.button) {
  20926. case 0:
  20927. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20928. break;
  20929. case 1:
  20930. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20931. break;
  20932. case 2:
  20933. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20934. break;
  20935. }
  20936. }
  20937. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20938. window.setTimeout(function () {
  20939. 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);
  20940. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20941. if (_this._totalPointersPressed !== 0 &&
  20942. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20943. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20944. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20945. _this._startingPointerTime = 0;
  20946. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20947. }
  20948. }
  20949. }, Scene.LongPressDelay);
  20950. }
  20951. }
  20952. }
  20953. if (pickResult) {
  20954. if (this.onPointerDown) {
  20955. this.onPointerDown(evt, pickResult);
  20956. }
  20957. if (this.onPointerObservable.hasObservers()) {
  20958. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20959. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20960. this.onPointerObservable.notifyObservers(pi, type);
  20961. }
  20962. }
  20963. return this;
  20964. };
  20965. /**
  20966. * Use this method to simulate a pointer up on a mesh
  20967. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20968. */
  20969. Scene.prototype.simulatePointerUp = function (pickResult) {
  20970. var evt = new PointerEvent("pointerup");
  20971. var clickInfo = new ClickInfo();
  20972. clickInfo.singleClick = true;
  20973. clickInfo.ignore = true;
  20974. return this._processPointerUp(pickResult, evt, clickInfo);
  20975. };
  20976. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20977. if (pickResult && pickResult && pickResult.pickedMesh) {
  20978. this._pickedUpMesh = pickResult.pickedMesh;
  20979. if (this._pickedDownMesh === this._pickedUpMesh) {
  20980. if (this.onPointerPick) {
  20981. this.onPointerPick(evt, pickResult);
  20982. }
  20983. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20984. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20985. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20986. this.onPointerObservable.notifyObservers(pi, type);
  20987. }
  20988. }
  20989. if (pickResult.pickedMesh.actionManager) {
  20990. if (clickInfo.ignore) {
  20991. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20992. }
  20993. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20994. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20995. }
  20996. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20997. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20998. }
  20999. }
  21000. }
  21001. if (this._pickedDownMesh &&
  21002. this._pickedDownMesh.actionManager &&
  21003. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21004. this._pickedDownMesh !== this._pickedUpMesh) {
  21005. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21006. }
  21007. if (this.onPointerUp) {
  21008. this.onPointerUp(evt, pickResult);
  21009. }
  21010. if (this.onPointerObservable.hasObservers()) {
  21011. if (!clickInfo.ignore) {
  21012. if (!clickInfo.hasSwiped) {
  21013. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21014. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21015. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21016. this.onPointerObservable.notifyObservers(pi, type);
  21017. }
  21018. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21019. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21020. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21021. this.onPointerObservable.notifyObservers(pi, type);
  21022. }
  21023. }
  21024. }
  21025. else {
  21026. var type = BABYLON.PointerEventTypes.POINTERUP;
  21027. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21028. this.onPointerObservable.notifyObservers(pi, type);
  21029. }
  21030. }
  21031. return this;
  21032. };
  21033. /**
  21034. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21035. * @param attachUp defines if you want to attach events to pointerup
  21036. * @param attachDown defines if you want to attach events to pointerdown
  21037. * @param attachMove defines if you want to attach events to pointermove
  21038. */
  21039. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21040. var _this = this;
  21041. if (attachUp === void 0) { attachUp = true; }
  21042. if (attachDown === void 0) { attachDown = true; }
  21043. if (attachMove === void 0) { attachMove = true; }
  21044. this._initActionManager = function (act, clickInfo) {
  21045. if (!_this._meshPickProceed) {
  21046. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21047. _this._currentPickResult = pickResult;
  21048. if (pickResult) {
  21049. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21050. }
  21051. _this._meshPickProceed = true;
  21052. }
  21053. return act;
  21054. };
  21055. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21056. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21057. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21058. btn !== _this._previousButtonPressed) {
  21059. _this._doubleClickOccured = false;
  21060. clickInfo.singleClick = true;
  21061. clickInfo.ignore = false;
  21062. cb(clickInfo, _this._currentPickResult);
  21063. }
  21064. };
  21065. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21066. var clickInfo = new ClickInfo();
  21067. _this._currentPickResult = null;
  21068. var act = null;
  21069. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21070. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21071. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21072. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21073. act = _this._initActionManager(act, clickInfo);
  21074. if (act)
  21075. checkPicking = act.hasPickTriggers;
  21076. }
  21077. if (checkPicking) {
  21078. var btn = evt.button;
  21079. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21080. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21081. if (!clickInfo.hasSwiped) {
  21082. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21083. if (!checkSingleClickImmediately) {
  21084. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21085. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21086. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21087. act = _this._initActionManager(act, clickInfo);
  21088. if (act)
  21089. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21090. }
  21091. }
  21092. if (checkSingleClickImmediately) {
  21093. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21094. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21095. btn !== _this._previousButtonPressed) {
  21096. clickInfo.singleClick = true;
  21097. cb(clickInfo, _this._currentPickResult);
  21098. }
  21099. }
  21100. else {
  21101. // wait that no double click has been raised during the double click delay
  21102. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21103. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21104. }
  21105. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21106. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21107. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21108. act = _this._initActionManager(act, clickInfo);
  21109. if (act)
  21110. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21111. }
  21112. if (checkDoubleClick) {
  21113. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21114. if (btn === _this._previousButtonPressed &&
  21115. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21116. !_this._doubleClickOccured) {
  21117. // pointer has not moved for 2 clicks, it's a double click
  21118. if (!clickInfo.hasSwiped &&
  21119. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21120. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21121. _this._previousStartingPointerTime = 0;
  21122. _this._doubleClickOccured = true;
  21123. clickInfo.doubleClick = true;
  21124. clickInfo.ignore = false;
  21125. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21126. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21127. }
  21128. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21129. cb(clickInfo, _this._currentPickResult);
  21130. }
  21131. else {
  21132. _this._doubleClickOccured = false;
  21133. _this._previousStartingPointerTime = _this._startingPointerTime;
  21134. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21135. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21136. _this._previousButtonPressed = btn;
  21137. if (Scene.ExclusiveDoubleClickMode) {
  21138. if (_this._previousDelayedSimpleClickTimeout) {
  21139. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21140. }
  21141. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21142. cb(clickInfo, _this._previousPickResult);
  21143. }
  21144. else {
  21145. cb(clickInfo, _this._currentPickResult);
  21146. }
  21147. }
  21148. }
  21149. else {
  21150. _this._doubleClickOccured = false;
  21151. _this._previousStartingPointerTime = _this._startingPointerTime;
  21152. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21153. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21154. _this._previousButtonPressed = btn;
  21155. }
  21156. }
  21157. }
  21158. }
  21159. clickInfo.ignore = true;
  21160. cb(clickInfo, _this._currentPickResult);
  21161. };
  21162. this._spritePredicate = function (sprite) {
  21163. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21164. };
  21165. this._onPointerMove = function (evt) {
  21166. _this._updatePointerPosition(evt);
  21167. // PreObservable support
  21168. if (_this.onPrePointerObservable.hasObservers()) {
  21169. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21170. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21171. _this.onPrePointerObservable.notifyObservers(pi, type);
  21172. if (pi.skipOnPointerObservable) {
  21173. return;
  21174. }
  21175. }
  21176. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21177. return;
  21178. }
  21179. if (!_this.pointerMovePredicate) {
  21180. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21181. }
  21182. // Meshes
  21183. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21184. _this._processPointerMove(pickResult, evt);
  21185. };
  21186. this._onPointerDown = function (evt) {
  21187. _this._totalPointersPressed++;
  21188. _this._pickedDownMesh = null;
  21189. _this._meshPickProceed = false;
  21190. _this._updatePointerPosition(evt);
  21191. if (_this.preventDefaultOnPointerDown && canvas) {
  21192. evt.preventDefault();
  21193. canvas.focus();
  21194. }
  21195. // PreObservable support
  21196. if (_this.onPrePointerObservable.hasObservers()) {
  21197. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21198. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21199. _this.onPrePointerObservable.notifyObservers(pi, type);
  21200. if (pi.skipOnPointerObservable) {
  21201. return;
  21202. }
  21203. }
  21204. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21205. return;
  21206. }
  21207. _this._startingPointerPosition.x = _this._pointerX;
  21208. _this._startingPointerPosition.y = _this._pointerY;
  21209. _this._startingPointerTime = new Date().getTime();
  21210. if (!_this.pointerDownPredicate) {
  21211. _this.pointerDownPredicate = function (mesh) {
  21212. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21213. };
  21214. }
  21215. // Meshes
  21216. _this._pickedDownMesh = null;
  21217. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21218. _this._processPointerDown(pickResult, evt);
  21219. // Sprites
  21220. _this._pickedDownSprite = null;
  21221. if (_this.spriteManagers.length > 0) {
  21222. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21223. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21224. if (pickResult.pickedSprite.actionManager) {
  21225. _this._pickedDownSprite = pickResult.pickedSprite;
  21226. switch (evt.button) {
  21227. case 0:
  21228. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21229. break;
  21230. case 1:
  21231. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21232. break;
  21233. case 2:
  21234. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21235. break;
  21236. }
  21237. if (pickResult.pickedSprite.actionManager) {
  21238. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21239. }
  21240. }
  21241. }
  21242. }
  21243. };
  21244. this._onPointerUp = function (evt) {
  21245. if (_this._totalPointersPressed === 0) {
  21246. return; // So we need to test it the pointer down was pressed before.
  21247. }
  21248. _this._totalPointersPressed--;
  21249. _this._pickedUpMesh = null;
  21250. _this._meshPickProceed = false;
  21251. _this._updatePointerPosition(evt);
  21252. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21253. // PreObservable support
  21254. if (_this.onPrePointerObservable.hasObservers()) {
  21255. if (!clickInfo.ignore) {
  21256. if (!clickInfo.hasSwiped) {
  21257. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21258. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21259. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21260. _this.onPrePointerObservable.notifyObservers(pi, type);
  21261. if (pi.skipOnPointerObservable) {
  21262. return;
  21263. }
  21264. }
  21265. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21266. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21267. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21268. _this.onPrePointerObservable.notifyObservers(pi, type);
  21269. if (pi.skipOnPointerObservable) {
  21270. return;
  21271. }
  21272. }
  21273. }
  21274. }
  21275. else {
  21276. var type = BABYLON.PointerEventTypes.POINTERUP;
  21277. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21278. _this.onPrePointerObservable.notifyObservers(pi, type);
  21279. if (pi.skipOnPointerObservable) {
  21280. return;
  21281. }
  21282. }
  21283. }
  21284. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21285. return;
  21286. }
  21287. if (!_this.pointerUpPredicate) {
  21288. _this.pointerUpPredicate = function (mesh) {
  21289. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21290. };
  21291. }
  21292. // Meshes
  21293. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21294. _this._initActionManager(null, clickInfo);
  21295. }
  21296. if (!pickResult) {
  21297. pickResult = _this._currentPickResult;
  21298. }
  21299. _this._processPointerUp(pickResult, evt, clickInfo);
  21300. // Sprites
  21301. if (_this.spriteManagers.length > 0) {
  21302. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21303. if (spritePickResult) {
  21304. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21305. if (spritePickResult.pickedSprite.actionManager) {
  21306. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21307. if (spritePickResult.pickedSprite.actionManager) {
  21308. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21309. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21310. }
  21311. }
  21312. }
  21313. }
  21314. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21315. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21316. }
  21317. }
  21318. }
  21319. _this._previousPickResult = _this._currentPickResult;
  21320. });
  21321. };
  21322. this._onKeyDown = function (evt) {
  21323. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21324. if (_this.onPreKeyboardObservable.hasObservers()) {
  21325. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21326. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21327. if (pi.skipOnPointerObservable) {
  21328. return;
  21329. }
  21330. }
  21331. if (_this.onKeyboardObservable.hasObservers()) {
  21332. var pi = new BABYLON.KeyboardInfo(type, evt);
  21333. _this.onKeyboardObservable.notifyObservers(pi, type);
  21334. }
  21335. if (_this.actionManager) {
  21336. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21337. }
  21338. };
  21339. this._onKeyUp = function (evt) {
  21340. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21341. if (_this.onPreKeyboardObservable.hasObservers()) {
  21342. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21343. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21344. if (pi.skipOnPointerObservable) {
  21345. return;
  21346. }
  21347. }
  21348. if (_this.onKeyboardObservable.hasObservers()) {
  21349. var pi = new BABYLON.KeyboardInfo(type, evt);
  21350. _this.onKeyboardObservable.notifyObservers(pi, type);
  21351. }
  21352. if (_this.actionManager) {
  21353. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21354. }
  21355. };
  21356. var engine = this.getEngine();
  21357. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21358. if (!canvas) {
  21359. return;
  21360. }
  21361. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21362. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21363. });
  21364. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21365. if (!canvas) {
  21366. return;
  21367. }
  21368. canvas.removeEventListener("keydown", _this._onKeyDown);
  21369. canvas.removeEventListener("keyup", _this._onKeyUp);
  21370. });
  21371. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21372. var canvas = this._engine.getRenderingCanvas();
  21373. if (!canvas) {
  21374. return;
  21375. }
  21376. if (attachMove) {
  21377. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21378. // Wheel
  21379. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21380. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21381. }
  21382. if (attachDown) {
  21383. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21384. }
  21385. if (attachUp) {
  21386. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21387. }
  21388. canvas.tabIndex = 1;
  21389. };
  21390. Scene.prototype.detachControl = function () {
  21391. var engine = this.getEngine();
  21392. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21393. var canvas = engine.getRenderingCanvas();
  21394. if (!canvas) {
  21395. return;
  21396. }
  21397. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21398. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21399. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21400. if (this._onCanvasBlurObserver) {
  21401. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21402. }
  21403. if (this._onCanvasFocusObserver) {
  21404. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21405. }
  21406. // Wheel
  21407. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21408. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21409. // Keyboard
  21410. canvas.removeEventListener("keydown", this._onKeyDown);
  21411. canvas.removeEventListener("keyup", this._onKeyUp);
  21412. // Observables
  21413. this.onKeyboardObservable.clear();
  21414. this.onPreKeyboardObservable.clear();
  21415. this.onPointerObservable.clear();
  21416. this.onPrePointerObservable.clear();
  21417. };
  21418. /**
  21419. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21420. * Delay loaded resources are not taking in account
  21421. * @return true if all required resources are ready
  21422. */
  21423. Scene.prototype.isReady = function () {
  21424. if (this._isDisposed) {
  21425. return false;
  21426. }
  21427. if (this._pendingData.length > 0) {
  21428. return false;
  21429. }
  21430. var index;
  21431. var engine = this.getEngine();
  21432. // Geometries
  21433. for (index = 0; index < this._geometries.length; index++) {
  21434. var geometry = this._geometries[index];
  21435. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21436. return false;
  21437. }
  21438. }
  21439. // Meshes
  21440. for (index = 0; index < this.meshes.length; index++) {
  21441. var mesh = this.meshes[index];
  21442. if (!mesh.isEnabled()) {
  21443. continue;
  21444. }
  21445. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21446. continue;
  21447. }
  21448. if (!mesh.isReady()) {
  21449. return false;
  21450. }
  21451. // Highlight layers
  21452. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21453. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21454. var layer = _a[_i];
  21455. if (!layer.hasMesh(mesh)) {
  21456. continue;
  21457. }
  21458. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21459. var subMesh = _c[_b];
  21460. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21461. return false;
  21462. }
  21463. }
  21464. }
  21465. }
  21466. return true;
  21467. };
  21468. Scene.prototype.resetCachedMaterial = function () {
  21469. this._cachedMaterial = null;
  21470. this._cachedEffect = null;
  21471. this._cachedVisibility = null;
  21472. };
  21473. Scene.prototype.registerBeforeRender = function (func) {
  21474. this.onBeforeRenderObservable.add(func);
  21475. };
  21476. Scene.prototype.unregisterBeforeRender = function (func) {
  21477. this.onBeforeRenderObservable.removeCallback(func);
  21478. };
  21479. Scene.prototype.registerAfterRender = function (func) {
  21480. this.onAfterRenderObservable.add(func);
  21481. };
  21482. Scene.prototype.unregisterAfterRender = function (func) {
  21483. this.onAfterRenderObservable.removeCallback(func);
  21484. };
  21485. Scene.prototype._executeOnceBeforeRender = function (func) {
  21486. var _this = this;
  21487. var execFunc = function () {
  21488. func();
  21489. setTimeout(function () {
  21490. _this.unregisterBeforeRender(execFunc);
  21491. });
  21492. };
  21493. this.registerBeforeRender(execFunc);
  21494. };
  21495. /**
  21496. * The provided function will run before render once and will be disposed afterwards.
  21497. * A timeout delay can be provided so that the function will be executed in N ms.
  21498. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21499. * @param func The function to be executed.
  21500. * @param timeout optional delay in ms
  21501. */
  21502. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21503. var _this = this;
  21504. if (timeout !== undefined) {
  21505. setTimeout(function () {
  21506. _this._executeOnceBeforeRender(func);
  21507. }, timeout);
  21508. }
  21509. else {
  21510. this._executeOnceBeforeRender(func);
  21511. }
  21512. };
  21513. Scene.prototype._addPendingData = function (data) {
  21514. this._pendingData.push(data);
  21515. };
  21516. Scene.prototype._removePendingData = function (data) {
  21517. var wasLoading = this.isLoading;
  21518. var index = this._pendingData.indexOf(data);
  21519. if (index !== -1) {
  21520. this._pendingData.splice(index, 1);
  21521. }
  21522. if (wasLoading && !this.isLoading) {
  21523. this.onDataLoadedObservable.notifyObservers(this);
  21524. }
  21525. };
  21526. Scene.prototype.getWaitingItemsCount = function () {
  21527. return this._pendingData.length;
  21528. };
  21529. Object.defineProperty(Scene.prototype, "isLoading", {
  21530. get: function () {
  21531. return this._pendingData.length > 0;
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. /**
  21537. * Registers a function to be executed when the scene is ready.
  21538. * @param {Function} func - the function to be executed.
  21539. */
  21540. Scene.prototype.executeWhenReady = function (func) {
  21541. var _this = this;
  21542. this.onReadyObservable.add(func);
  21543. if (this._executeWhenReadyTimeoutId !== -1) {
  21544. return;
  21545. }
  21546. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21547. _this._checkIsReady();
  21548. }, 150);
  21549. };
  21550. Scene.prototype._checkIsReady = function () {
  21551. var _this = this;
  21552. if (this.isReady()) {
  21553. this.onReadyObservable.notifyObservers(this);
  21554. this.onReadyObservable.clear();
  21555. this._executeWhenReadyTimeoutId = -1;
  21556. return;
  21557. }
  21558. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21559. _this._checkIsReady();
  21560. }, 150);
  21561. };
  21562. // Animations
  21563. /**
  21564. * Will start the animation sequence of a given target
  21565. * @param target - the target
  21566. * @param {number} from - from which frame should animation start
  21567. * @param {number} to - till which frame should animation run.
  21568. * @param {boolean} [loop] - should the animation loop
  21569. * @param {number} [speedRatio] - the speed in which to run the animation
  21570. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21571. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21572. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21573. * See BABYLON.Animatable
  21574. */
  21575. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21576. if (speedRatio === void 0) { speedRatio = 1.0; }
  21577. if (from > to && speedRatio > 0) {
  21578. speedRatio *= -1;
  21579. }
  21580. this.stopAnimation(target);
  21581. if (!animatable) {
  21582. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21583. }
  21584. // Local animations
  21585. if (target.animations) {
  21586. animatable.appendAnimations(target, target.animations);
  21587. }
  21588. // Children animations
  21589. if (target.getAnimatables) {
  21590. var animatables = target.getAnimatables();
  21591. for (var index = 0; index < animatables.length; index++) {
  21592. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21593. }
  21594. }
  21595. animatable.reset();
  21596. return animatable;
  21597. };
  21598. /**
  21599. * Begin a new animation on a given node
  21600. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21601. * @param {BABYLON.Animation[]} defines the list of animations to start
  21602. * @param {number} from defines the initial value
  21603. * @param {number} to defines the final value
  21604. * @param {boolean} loop defines if you want animation to loop (off by default)
  21605. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21606. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21607. * @returns the list of created animatables
  21608. */
  21609. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21610. if (speedRatio === undefined) {
  21611. speedRatio = 1.0;
  21612. }
  21613. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21614. return animatable;
  21615. };
  21616. /**
  21617. * Begin a new animation on a given node and its hierarchy
  21618. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21619. * @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.
  21620. * @param {BABYLON.Animation[]} defines the list of animations to start
  21621. * @param {number} from defines the initial value
  21622. * @param {number} to defines the final value
  21623. * @param {boolean} loop defines if you want animation to loop (off by default)
  21624. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21625. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21626. * @returns the list of animatables created for all nodes
  21627. */
  21628. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21629. var children = target.getDescendants(directDescendantsOnly);
  21630. var result = [];
  21631. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21632. var child = children_1[_i];
  21633. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21634. }
  21635. return result;
  21636. };
  21637. Scene.prototype.getAnimatableByTarget = function (target) {
  21638. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21639. if (this._activeAnimatables[index].target === target) {
  21640. return this._activeAnimatables[index];
  21641. }
  21642. }
  21643. return null;
  21644. };
  21645. Object.defineProperty(Scene.prototype, "animatables", {
  21646. get: function () {
  21647. return this._activeAnimatables;
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. /**
  21653. * Will stop the animation of the given target
  21654. * @param target - the target
  21655. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21656. * @see beginAnimation
  21657. */
  21658. Scene.prototype.stopAnimation = function (target, animationName) {
  21659. var animatable = this.getAnimatableByTarget(target);
  21660. if (animatable) {
  21661. animatable.stop(animationName);
  21662. }
  21663. };
  21664. /**
  21665. * Stops and removes all animations that have been applied to the scene
  21666. */
  21667. Scene.prototype.stopAllAnimations = function () {
  21668. if (this._activeAnimatables) {
  21669. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21670. this._activeAnimatables[i].stop();
  21671. }
  21672. this._activeAnimatables = [];
  21673. }
  21674. };
  21675. Scene.prototype._animate = function () {
  21676. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21677. return;
  21678. }
  21679. // Getting time
  21680. var now = BABYLON.Tools.Now;
  21681. if (!this._animationTimeLast) {
  21682. if (this._pendingData.length > 0) {
  21683. return;
  21684. }
  21685. this._animationTimeLast = now;
  21686. }
  21687. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21688. this._animationTime += deltaTime;
  21689. this._animationTimeLast = now;
  21690. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21691. this._activeAnimatables[index]._animate(this._animationTime);
  21692. }
  21693. };
  21694. // Matrix
  21695. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21696. this._useAlternateCameraConfiguration = active;
  21697. };
  21698. Scene.prototype.getViewMatrix = function () {
  21699. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21700. };
  21701. Scene.prototype.getProjectionMatrix = function () {
  21702. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21703. };
  21704. Scene.prototype.getTransformMatrix = function () {
  21705. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21706. };
  21707. Scene.prototype.setTransformMatrix = function (view, projection) {
  21708. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21709. return;
  21710. }
  21711. this._viewUpdateFlag = view.updateFlag;
  21712. this._projectionUpdateFlag = projection.updateFlag;
  21713. this._viewMatrix = view;
  21714. this._projectionMatrix = projection;
  21715. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21716. // Update frustum
  21717. if (!this._frustumPlanes) {
  21718. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21719. }
  21720. else {
  21721. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21722. }
  21723. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21724. var otherCamera = this.activeCamera._alternateCamera;
  21725. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21726. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21727. }
  21728. if (this._sceneUbo.useUbo) {
  21729. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21730. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21731. this._sceneUbo.update();
  21732. }
  21733. };
  21734. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21735. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21736. return;
  21737. }
  21738. this._alternateViewUpdateFlag = view.updateFlag;
  21739. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21740. this._alternateViewMatrix = view;
  21741. this._alternateProjectionMatrix = projection;
  21742. if (!this._alternateTransformMatrix) {
  21743. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21744. }
  21745. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21746. if (!this._alternateSceneUbo) {
  21747. this._createAlternateUbo();
  21748. }
  21749. if (this._alternateSceneUbo.useUbo) {
  21750. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21751. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21752. this._alternateSceneUbo.update();
  21753. }
  21754. };
  21755. Scene.prototype.getSceneUniformBuffer = function () {
  21756. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21757. };
  21758. // Methods
  21759. Scene.prototype.getUniqueId = function () {
  21760. var result = Scene._uniqueIdCounter;
  21761. Scene._uniqueIdCounter++;
  21762. return result;
  21763. };
  21764. Scene.prototype.addMesh = function (newMesh) {
  21765. this.meshes.push(newMesh);
  21766. //notify the collision coordinator
  21767. if (this.collisionCoordinator) {
  21768. this.collisionCoordinator.onMeshAdded(newMesh);
  21769. }
  21770. newMesh._resyncLightSources();
  21771. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21772. };
  21773. Scene.prototype.removeMesh = function (toRemove) {
  21774. var index = this.meshes.indexOf(toRemove);
  21775. if (index !== -1) {
  21776. // Remove from the scene if mesh found
  21777. this.meshes.splice(index, 1);
  21778. }
  21779. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21780. return index;
  21781. };
  21782. Scene.prototype.addTransformNode = function (newTransformNode) {
  21783. this.transformNodes.push(newTransformNode);
  21784. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21785. };
  21786. Scene.prototype.removeTransformNode = function (toRemove) {
  21787. var index = this.transformNodes.indexOf(toRemove);
  21788. if (index !== -1) {
  21789. // Remove from the scene if found
  21790. this.transformNodes.splice(index, 1);
  21791. }
  21792. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21793. return index;
  21794. };
  21795. Scene.prototype.removeSkeleton = function (toRemove) {
  21796. var index = this.skeletons.indexOf(toRemove);
  21797. if (index !== -1) {
  21798. // Remove from the scene if found
  21799. this.skeletons.splice(index, 1);
  21800. }
  21801. return index;
  21802. };
  21803. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21804. var index = this.morphTargetManagers.indexOf(toRemove);
  21805. if (index !== -1) {
  21806. // Remove from the scene if found
  21807. this.morphTargetManagers.splice(index, 1);
  21808. }
  21809. return index;
  21810. };
  21811. Scene.prototype.removeLight = function (toRemove) {
  21812. var index = this.lights.indexOf(toRemove);
  21813. if (index !== -1) {
  21814. // Remove from meshes
  21815. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21816. var mesh = _a[_i];
  21817. mesh._removeLightSource(toRemove);
  21818. }
  21819. // Remove from the scene if mesh found
  21820. this.lights.splice(index, 1);
  21821. this.sortLightsByPriority();
  21822. }
  21823. this.onLightRemovedObservable.notifyObservers(toRemove);
  21824. return index;
  21825. };
  21826. Scene.prototype.removeCamera = function (toRemove) {
  21827. var index = this.cameras.indexOf(toRemove);
  21828. if (index !== -1) {
  21829. // Remove from the scene if mesh found
  21830. this.cameras.splice(index, 1);
  21831. }
  21832. // Remove from activeCameras
  21833. var index2 = this.activeCameras.indexOf(toRemove);
  21834. if (index2 !== -1) {
  21835. // Remove from the scene if mesh found
  21836. this.activeCameras.splice(index2, 1);
  21837. }
  21838. // Reset the activeCamera
  21839. if (this.activeCamera === toRemove) {
  21840. if (this.cameras.length > 0) {
  21841. this.activeCamera = this.cameras[0];
  21842. }
  21843. else {
  21844. this.activeCamera = null;
  21845. }
  21846. }
  21847. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21848. return index;
  21849. };
  21850. Scene.prototype.removeParticleSystem = function (toRemove) {
  21851. var index = this.particleSystems.indexOf(toRemove);
  21852. if (index !== -1) {
  21853. this.particleSystems.splice(index, 1);
  21854. }
  21855. return index;
  21856. };
  21857. ;
  21858. Scene.prototype.removeAnimation = function (toRemove) {
  21859. var index = this.animations.indexOf(toRemove);
  21860. if (index !== -1) {
  21861. this.animations.splice(index, 1);
  21862. }
  21863. return index;
  21864. };
  21865. ;
  21866. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21867. var index = this.multiMaterials.indexOf(toRemove);
  21868. if (index !== -1) {
  21869. this.multiMaterials.splice(index, 1);
  21870. }
  21871. return index;
  21872. };
  21873. ;
  21874. Scene.prototype.removeMaterial = function (toRemove) {
  21875. var index = this.materials.indexOf(toRemove);
  21876. if (index !== -1) {
  21877. this.materials.splice(index, 1);
  21878. }
  21879. return index;
  21880. };
  21881. ;
  21882. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21883. var index = this.lensFlareSystems.indexOf(toRemove);
  21884. if (index !== -1) {
  21885. this.lensFlareSystems.splice(index, 1);
  21886. }
  21887. return index;
  21888. };
  21889. ;
  21890. Scene.prototype.removeActionManager = function (toRemove) {
  21891. var index = this._actionManagers.indexOf(toRemove);
  21892. if (index !== -1) {
  21893. this._actionManagers.splice(index, 1);
  21894. }
  21895. return index;
  21896. };
  21897. ;
  21898. Scene.prototype.addLight = function (newLight) {
  21899. this.lights.push(newLight);
  21900. this.sortLightsByPriority();
  21901. // Add light to all meshes (To support if the light is removed and then readded)
  21902. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21903. var mesh = _a[_i];
  21904. if (mesh._lightSources.indexOf(newLight) === -1) {
  21905. mesh._lightSources.push(newLight);
  21906. mesh._resyncLightSources();
  21907. }
  21908. }
  21909. this.onNewLightAddedObservable.notifyObservers(newLight);
  21910. };
  21911. Scene.prototype.sortLightsByPriority = function () {
  21912. if (this.requireLightSorting) {
  21913. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  21914. }
  21915. };
  21916. Scene.prototype.addCamera = function (newCamera) {
  21917. this.cameras.push(newCamera);
  21918. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21919. };
  21920. Scene.prototype.addSkeleton = function (newSkeleton) {
  21921. this.skeletons.push(newSkeleton);
  21922. };
  21923. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21924. this.particleSystems.push(newParticleSystem);
  21925. };
  21926. Scene.prototype.addAnimation = function (newAnimation) {
  21927. this.animations.push(newAnimation);
  21928. };
  21929. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21930. this.multiMaterials.push(newMultiMaterial);
  21931. };
  21932. Scene.prototype.addMaterial = function (newMaterial) {
  21933. this.materials.push(newMaterial);
  21934. };
  21935. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21936. this.morphTargetManagers.push(newMorphTargetManager);
  21937. };
  21938. Scene.prototype.addGeometry = function (newGeometrie) {
  21939. this._geometries.push(newGeometrie);
  21940. };
  21941. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21942. this.lensFlareSystems.push(newLensFlareSystem);
  21943. };
  21944. Scene.prototype.addActionManager = function (newActionManager) {
  21945. this._actionManagers.push(newActionManager);
  21946. };
  21947. /**
  21948. * Switch active camera
  21949. * @param {Camera} newCamera - new active camera
  21950. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21951. */
  21952. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21953. if (attachControl === void 0) { attachControl = true; }
  21954. var canvas = this._engine.getRenderingCanvas();
  21955. if (!canvas) {
  21956. return;
  21957. }
  21958. if (this.activeCamera) {
  21959. this.activeCamera.detachControl(canvas);
  21960. }
  21961. this.activeCamera = newCamera;
  21962. if (attachControl) {
  21963. newCamera.attachControl(canvas);
  21964. }
  21965. };
  21966. /**
  21967. * sets the active camera of the scene using its ID
  21968. * @param {string} id - the camera's ID
  21969. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21970. * @see activeCamera
  21971. */
  21972. Scene.prototype.setActiveCameraByID = function (id) {
  21973. var camera = this.getCameraByID(id);
  21974. if (camera) {
  21975. this.activeCamera = camera;
  21976. return camera;
  21977. }
  21978. return null;
  21979. };
  21980. /**
  21981. * sets the active camera of the scene using its name
  21982. * @param {string} name - the camera's name
  21983. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21984. * @see activeCamera
  21985. */
  21986. Scene.prototype.setActiveCameraByName = function (name) {
  21987. var camera = this.getCameraByName(name);
  21988. if (camera) {
  21989. this.activeCamera = camera;
  21990. return camera;
  21991. }
  21992. return null;
  21993. };
  21994. /**
  21995. * get an animation group using its name
  21996. * @param {string} the material's name
  21997. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21998. */
  21999. Scene.prototype.getAnimationGroupByName = function (name) {
  22000. for (var index = 0; index < this.animationGroups.length; index++) {
  22001. if (this.animationGroups[index].name === name) {
  22002. return this.animationGroups[index];
  22003. }
  22004. }
  22005. return null;
  22006. };
  22007. /**
  22008. * get a material using its id
  22009. * @param {string} the material's ID
  22010. * @return {BABYLON.Material|null} the material or null if none found.
  22011. */
  22012. Scene.prototype.getMaterialByID = function (id) {
  22013. for (var index = 0; index < this.materials.length; index++) {
  22014. if (this.materials[index].id === id) {
  22015. return this.materials[index];
  22016. }
  22017. }
  22018. return null;
  22019. };
  22020. /**
  22021. * get a material using its name
  22022. * @param {string} the material's name
  22023. * @return {BABYLON.Material|null} the material or null if none found.
  22024. */
  22025. Scene.prototype.getMaterialByName = function (name) {
  22026. for (var index = 0; index < this.materials.length; index++) {
  22027. if (this.materials[index].name === name) {
  22028. return this.materials[index];
  22029. }
  22030. }
  22031. return null;
  22032. };
  22033. Scene.prototype.getLensFlareSystemByName = function (name) {
  22034. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22035. if (this.lensFlareSystems[index].name === name) {
  22036. return this.lensFlareSystems[index];
  22037. }
  22038. }
  22039. return null;
  22040. };
  22041. Scene.prototype.getLensFlareSystemByID = function (id) {
  22042. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22043. if (this.lensFlareSystems[index].id === id) {
  22044. return this.lensFlareSystems[index];
  22045. }
  22046. }
  22047. return null;
  22048. };
  22049. Scene.prototype.getCameraByID = function (id) {
  22050. for (var index = 0; index < this.cameras.length; index++) {
  22051. if (this.cameras[index].id === id) {
  22052. return this.cameras[index];
  22053. }
  22054. }
  22055. return null;
  22056. };
  22057. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22058. for (var index = 0; index < this.cameras.length; index++) {
  22059. if (this.cameras[index].uniqueId === uniqueId) {
  22060. return this.cameras[index];
  22061. }
  22062. }
  22063. return null;
  22064. };
  22065. /**
  22066. * get a camera using its name
  22067. * @param {string} the camera's name
  22068. * @return {BABYLON.Camera|null} the camera or null if none found.
  22069. */
  22070. Scene.prototype.getCameraByName = function (name) {
  22071. for (var index = 0; index < this.cameras.length; index++) {
  22072. if (this.cameras[index].name === name) {
  22073. return this.cameras[index];
  22074. }
  22075. }
  22076. return null;
  22077. };
  22078. /**
  22079. * get a bone using its id
  22080. * @param {string} the bone's id
  22081. * @return {BABYLON.Bone|null} the bone or null if not found
  22082. */
  22083. Scene.prototype.getBoneByID = function (id) {
  22084. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22085. var skeleton = this.skeletons[skeletonIndex];
  22086. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22087. if (skeleton.bones[boneIndex].id === id) {
  22088. return skeleton.bones[boneIndex];
  22089. }
  22090. }
  22091. }
  22092. return null;
  22093. };
  22094. /**
  22095. * get a bone using its id
  22096. * @param {string} the bone's name
  22097. * @return {BABYLON.Bone|null} the bone or null if not found
  22098. */
  22099. Scene.prototype.getBoneByName = function (name) {
  22100. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22101. var skeleton = this.skeletons[skeletonIndex];
  22102. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22103. if (skeleton.bones[boneIndex].name === name) {
  22104. return skeleton.bones[boneIndex];
  22105. }
  22106. }
  22107. }
  22108. return null;
  22109. };
  22110. /**
  22111. * get a light node using its name
  22112. * @param {string} the light's name
  22113. * @return {BABYLON.Light|null} the light or null if none found.
  22114. */
  22115. Scene.prototype.getLightByName = function (name) {
  22116. for (var index = 0; index < this.lights.length; index++) {
  22117. if (this.lights[index].name === name) {
  22118. return this.lights[index];
  22119. }
  22120. }
  22121. return null;
  22122. };
  22123. /**
  22124. * get a light node using its ID
  22125. * @param {string} the light's id
  22126. * @return {BABYLON.Light|null} the light or null if none found.
  22127. */
  22128. Scene.prototype.getLightByID = function (id) {
  22129. for (var index = 0; index < this.lights.length; index++) {
  22130. if (this.lights[index].id === id) {
  22131. return this.lights[index];
  22132. }
  22133. }
  22134. return null;
  22135. };
  22136. /**
  22137. * get a light node using its scene-generated unique ID
  22138. * @param {number} the light's unique id
  22139. * @return {BABYLON.Light|null} the light or null if none found.
  22140. */
  22141. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22142. for (var index = 0; index < this.lights.length; index++) {
  22143. if (this.lights[index].uniqueId === uniqueId) {
  22144. return this.lights[index];
  22145. }
  22146. }
  22147. return null;
  22148. };
  22149. /**
  22150. * get a particle system by id
  22151. * @param id {number} the particle system id
  22152. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22153. */
  22154. Scene.prototype.getParticleSystemByID = function (id) {
  22155. for (var index = 0; index < this.particleSystems.length; index++) {
  22156. if (this.particleSystems[index].id === id) {
  22157. return this.particleSystems[index];
  22158. }
  22159. }
  22160. return null;
  22161. };
  22162. /**
  22163. * get a geometry using its ID
  22164. * @param {string} the geometry's id
  22165. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22166. */
  22167. Scene.prototype.getGeometryByID = function (id) {
  22168. for (var index = 0; index < this._geometries.length; index++) {
  22169. if (this._geometries[index].id === id) {
  22170. return this._geometries[index];
  22171. }
  22172. }
  22173. return null;
  22174. };
  22175. /**
  22176. * add a new geometry to this scene.
  22177. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22178. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22179. * @return {boolean} was the geometry added or not
  22180. */
  22181. Scene.prototype.pushGeometry = function (geometry, force) {
  22182. if (!force && this.getGeometryByID(geometry.id)) {
  22183. return false;
  22184. }
  22185. this._geometries.push(geometry);
  22186. //notify the collision coordinator
  22187. if (this.collisionCoordinator) {
  22188. this.collisionCoordinator.onGeometryAdded(geometry);
  22189. }
  22190. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22191. return true;
  22192. };
  22193. /**
  22194. * Removes an existing geometry
  22195. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22196. * @return {boolean} was the geometry removed or not
  22197. */
  22198. Scene.prototype.removeGeometry = function (geometry) {
  22199. var index = this._geometries.indexOf(geometry);
  22200. if (index > -1) {
  22201. this._geometries.splice(index, 1);
  22202. //notify the collision coordinator
  22203. if (this.collisionCoordinator) {
  22204. this.collisionCoordinator.onGeometryDeleted(geometry);
  22205. }
  22206. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22207. return true;
  22208. }
  22209. return false;
  22210. };
  22211. Scene.prototype.getGeometries = function () {
  22212. return this._geometries;
  22213. };
  22214. /**
  22215. * Get the first added mesh found of a given ID
  22216. * @param {string} id - the id to search for
  22217. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22218. */
  22219. Scene.prototype.getMeshByID = function (id) {
  22220. for (var index = 0; index < this.meshes.length; index++) {
  22221. if (this.meshes[index].id === id) {
  22222. return this.meshes[index];
  22223. }
  22224. }
  22225. return null;
  22226. };
  22227. Scene.prototype.getMeshesByID = function (id) {
  22228. return this.meshes.filter(function (m) {
  22229. return m.id === id;
  22230. });
  22231. };
  22232. /**
  22233. * Get the first added transform node found of a given ID
  22234. * @param {string} id - the id to search for
  22235. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22236. */
  22237. Scene.prototype.getTransformNodeByID = function (id) {
  22238. for (var index = 0; index < this.transformNodes.length; index++) {
  22239. if (this.transformNodes[index].id === id) {
  22240. return this.transformNodes[index];
  22241. }
  22242. }
  22243. return null;
  22244. };
  22245. Scene.prototype.getTransformNodesByID = function (id) {
  22246. return this.transformNodes.filter(function (m) {
  22247. return m.id === id;
  22248. });
  22249. };
  22250. /**
  22251. * Get a mesh with its auto-generated unique id
  22252. * @param {number} uniqueId - the unique id to search for
  22253. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22254. */
  22255. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22256. for (var index = 0; index < this.meshes.length; index++) {
  22257. if (this.meshes[index].uniqueId === uniqueId) {
  22258. return this.meshes[index];
  22259. }
  22260. }
  22261. return null;
  22262. };
  22263. /**
  22264. * Get a the last added mesh found of a given ID
  22265. * @param {string} id - the id to search for
  22266. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22267. */
  22268. Scene.prototype.getLastMeshByID = function (id) {
  22269. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22270. if (this.meshes[index].id === id) {
  22271. return this.meshes[index];
  22272. }
  22273. }
  22274. return null;
  22275. };
  22276. /**
  22277. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22278. * @param {string} id - the id to search for
  22279. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22280. */
  22281. Scene.prototype.getLastEntryByID = function (id) {
  22282. var index;
  22283. for (index = this.meshes.length - 1; index >= 0; index--) {
  22284. if (this.meshes[index].id === id) {
  22285. return this.meshes[index];
  22286. }
  22287. }
  22288. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22289. if (this.transformNodes[index].id === id) {
  22290. return this.transformNodes[index];
  22291. }
  22292. }
  22293. for (index = this.cameras.length - 1; index >= 0; index--) {
  22294. if (this.cameras[index].id === id) {
  22295. return this.cameras[index];
  22296. }
  22297. }
  22298. for (index = this.lights.length - 1; index >= 0; index--) {
  22299. if (this.lights[index].id === id) {
  22300. return this.lights[index];
  22301. }
  22302. }
  22303. return null;
  22304. };
  22305. Scene.prototype.getNodeByID = function (id) {
  22306. var mesh = this.getMeshByID(id);
  22307. if (mesh) {
  22308. return mesh;
  22309. }
  22310. var light = this.getLightByID(id);
  22311. if (light) {
  22312. return light;
  22313. }
  22314. var camera = this.getCameraByID(id);
  22315. if (camera) {
  22316. return camera;
  22317. }
  22318. var bone = this.getBoneByID(id);
  22319. return bone;
  22320. };
  22321. Scene.prototype.getNodeByName = function (name) {
  22322. var mesh = this.getMeshByName(name);
  22323. if (mesh) {
  22324. return mesh;
  22325. }
  22326. var light = this.getLightByName(name);
  22327. if (light) {
  22328. return light;
  22329. }
  22330. var camera = this.getCameraByName(name);
  22331. if (camera) {
  22332. return camera;
  22333. }
  22334. var bone = this.getBoneByName(name);
  22335. return bone;
  22336. };
  22337. Scene.prototype.getMeshByName = function (name) {
  22338. for (var index = 0; index < this.meshes.length; index++) {
  22339. if (this.meshes[index].name === name) {
  22340. return this.meshes[index];
  22341. }
  22342. }
  22343. return null;
  22344. };
  22345. Scene.prototype.getTransformNodeByName = function (name) {
  22346. for (var index = 0; index < this.transformNodes.length; index++) {
  22347. if (this.transformNodes[index].name === name) {
  22348. return this.transformNodes[index];
  22349. }
  22350. }
  22351. return null;
  22352. };
  22353. Scene.prototype.getSoundByName = function (name) {
  22354. var index;
  22355. if (BABYLON.AudioEngine) {
  22356. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22357. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22358. return this.mainSoundTrack.soundCollection[index];
  22359. }
  22360. }
  22361. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22362. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22363. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22364. return this.soundTracks[sdIndex].soundCollection[index];
  22365. }
  22366. }
  22367. }
  22368. }
  22369. return null;
  22370. };
  22371. Scene.prototype.getLastSkeletonByID = function (id) {
  22372. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22373. if (this.skeletons[index].id === id) {
  22374. return this.skeletons[index];
  22375. }
  22376. }
  22377. return null;
  22378. };
  22379. Scene.prototype.getSkeletonById = function (id) {
  22380. for (var index = 0; index < this.skeletons.length; index++) {
  22381. if (this.skeletons[index].id === id) {
  22382. return this.skeletons[index];
  22383. }
  22384. }
  22385. return null;
  22386. };
  22387. Scene.prototype.getSkeletonByName = function (name) {
  22388. for (var index = 0; index < this.skeletons.length; index++) {
  22389. if (this.skeletons[index].name === name) {
  22390. return this.skeletons[index];
  22391. }
  22392. }
  22393. return null;
  22394. };
  22395. Scene.prototype.getMorphTargetManagerById = function (id) {
  22396. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22397. if (this.morphTargetManagers[index].uniqueId === id) {
  22398. return this.morphTargetManagers[index];
  22399. }
  22400. }
  22401. return null;
  22402. };
  22403. Scene.prototype.isActiveMesh = function (mesh) {
  22404. return (this._activeMeshes.indexOf(mesh) !== -1);
  22405. };
  22406. /**
  22407. * Return a the first highlight layer of the scene with a given name.
  22408. * @param name The name of the highlight layer to look for.
  22409. * @return The highlight layer if found otherwise null.
  22410. */
  22411. Scene.prototype.getHighlightLayerByName = function (name) {
  22412. for (var index = 0; index < this.highlightLayers.length; index++) {
  22413. if (this.highlightLayers[index].name === name) {
  22414. return this.highlightLayers[index];
  22415. }
  22416. }
  22417. return null;
  22418. };
  22419. Object.defineProperty(Scene.prototype, "uid", {
  22420. /**
  22421. * Return a unique id as a string which can serve as an identifier for the scene
  22422. */
  22423. get: function () {
  22424. if (!this._uid) {
  22425. this._uid = BABYLON.Tools.RandomId();
  22426. }
  22427. return this._uid;
  22428. },
  22429. enumerable: true,
  22430. configurable: true
  22431. });
  22432. /**
  22433. * Add an externaly attached data from its key.
  22434. * This method call will fail and return false, if such key already exists.
  22435. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22436. * @param key the unique key that identifies the data
  22437. * @param data the data object to associate to the key for this Engine instance
  22438. * @return true if no such key were already present and the data was added successfully, false otherwise
  22439. */
  22440. Scene.prototype.addExternalData = function (key, data) {
  22441. if (!this._externalData) {
  22442. this._externalData = new BABYLON.StringDictionary();
  22443. }
  22444. return this._externalData.add(key, data);
  22445. };
  22446. /**
  22447. * Get an externaly attached data from its key
  22448. * @param key the unique key that identifies the data
  22449. * @return the associated data, if present (can be null), or undefined if not present
  22450. */
  22451. Scene.prototype.getExternalData = function (key) {
  22452. if (!this._externalData) {
  22453. return null;
  22454. }
  22455. return this._externalData.get(key);
  22456. };
  22457. /**
  22458. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22459. * @param key the unique key that identifies the data
  22460. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22461. * @return the associated data, can be null if the factory returned null.
  22462. */
  22463. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22464. if (!this._externalData) {
  22465. this._externalData = new BABYLON.StringDictionary();
  22466. }
  22467. return this._externalData.getOrAddWithFactory(key, factory);
  22468. };
  22469. /**
  22470. * Remove an externaly attached data from the Engine instance
  22471. * @param key the unique key that identifies the data
  22472. * @return true if the data was successfully removed, false if it doesn't exist
  22473. */
  22474. Scene.prototype.removeExternalData = function (key) {
  22475. return this._externalData.remove(key);
  22476. };
  22477. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22478. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22479. if (mesh.showSubMeshesBoundingBox) {
  22480. var boundingInfo = subMesh.getBoundingInfo();
  22481. if (boundingInfo !== null && boundingInfo !== undefined) {
  22482. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22483. }
  22484. }
  22485. var material = subMesh.getMaterial();
  22486. if (material !== null && material !== undefined) {
  22487. // Render targets
  22488. if (material.getRenderTargetTextures !== undefined) {
  22489. if (this._processedMaterials.indexOf(material) === -1) {
  22490. this._processedMaterials.push(material);
  22491. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22492. }
  22493. }
  22494. // Dispatch
  22495. this._activeIndices.addCount(subMesh.indexCount, false);
  22496. this._renderingManager.dispatch(subMesh, mesh, material);
  22497. }
  22498. }
  22499. };
  22500. Scene.prototype._isInIntermediateRendering = function () {
  22501. return this._intermediateRendering;
  22502. };
  22503. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22504. this._activeMeshCandidateProvider = provider;
  22505. };
  22506. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22507. return this._activeMeshCandidateProvider;
  22508. };
  22509. /**
  22510. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22511. */
  22512. Scene.prototype.freezeActiveMeshes = function () {
  22513. this._evaluateActiveMeshes();
  22514. this._activeMeshesFrozen = true;
  22515. return this;
  22516. };
  22517. /**
  22518. * Use this function to restart evaluating active meshes on every frame
  22519. */
  22520. Scene.prototype.unfreezeActiveMeshes = function () {
  22521. this._activeMeshesFrozen = false;
  22522. return this;
  22523. };
  22524. Scene.prototype._evaluateActiveMeshes = function () {
  22525. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22526. return;
  22527. }
  22528. if (!this.activeCamera) {
  22529. return;
  22530. }
  22531. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22532. this.activeCamera._activeMeshes.reset();
  22533. this._activeMeshes.reset();
  22534. this._renderingManager.reset();
  22535. this._processedMaterials.reset();
  22536. this._activeParticleSystems.reset();
  22537. this._activeSkeletons.reset();
  22538. this._softwareSkinnedMeshes.reset();
  22539. if (this._boundingBoxRenderer) {
  22540. this._boundingBoxRenderer.reset();
  22541. }
  22542. // Meshes
  22543. var meshes;
  22544. var len;
  22545. var checkIsEnabled = true;
  22546. // Determine mesh candidates
  22547. if (this._activeMeshCandidateProvider !== undefined) {
  22548. // Use _activeMeshCandidateProvider
  22549. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22550. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22551. if (meshes !== undefined) {
  22552. len = meshes.length;
  22553. }
  22554. else {
  22555. len = 0;
  22556. }
  22557. }
  22558. else if (this._selectionOctree !== undefined) {
  22559. // Octree
  22560. var selection = this._selectionOctree.select(this._frustumPlanes);
  22561. meshes = selection.data;
  22562. len = selection.length;
  22563. }
  22564. else {
  22565. // Full scene traversal
  22566. len = this.meshes.length;
  22567. meshes = this.meshes;
  22568. }
  22569. // Check each mesh
  22570. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22571. mesh = meshes[meshIndex];
  22572. if (mesh.isBlocked) {
  22573. continue;
  22574. }
  22575. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22576. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22577. continue;
  22578. }
  22579. mesh.computeWorldMatrix();
  22580. // Intersections
  22581. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22582. this._meshesForIntersections.pushNoDuplicate(mesh);
  22583. }
  22584. // Switch to current LOD
  22585. meshLOD = mesh.getLOD(this.activeCamera);
  22586. if (meshLOD === undefined || meshLOD === null) {
  22587. continue;
  22588. }
  22589. mesh._preActivate();
  22590. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22591. this._activeMeshes.push(mesh);
  22592. this.activeCamera._activeMeshes.push(mesh);
  22593. mesh._activate(this._renderId);
  22594. if (meshLOD !== mesh) {
  22595. meshLOD._activate(this._renderId);
  22596. }
  22597. this._activeMesh(mesh, meshLOD);
  22598. }
  22599. }
  22600. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22601. // Particle systems
  22602. if (this.particlesEnabled) {
  22603. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22604. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22605. var particleSystem = this.particleSystems[particleIndex];
  22606. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22607. continue;
  22608. }
  22609. var emitter = particleSystem.emitter;
  22610. if (!emitter.position || emitter.isEnabled()) {
  22611. this._activeParticleSystems.push(particleSystem);
  22612. particleSystem.animate();
  22613. this._renderingManager.dispatchParticles(particleSystem);
  22614. }
  22615. }
  22616. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22617. }
  22618. };
  22619. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22620. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22621. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22622. mesh.skeleton.prepare();
  22623. }
  22624. if (!mesh.computeBonesUsingShaders) {
  22625. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22626. }
  22627. }
  22628. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22629. var boundingInfo = sourceMesh.getBoundingInfo();
  22630. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22631. }
  22632. if (mesh !== undefined && mesh !== null
  22633. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22634. // Submeshes Octrees
  22635. var len;
  22636. var subMeshes;
  22637. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22638. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22639. len = intersections.length;
  22640. subMeshes = intersections.data;
  22641. }
  22642. else {
  22643. subMeshes = mesh.subMeshes;
  22644. len = subMeshes.length;
  22645. }
  22646. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22647. subMesh = subMeshes[subIndex];
  22648. this._evaluateSubMesh(subMesh, mesh);
  22649. }
  22650. }
  22651. };
  22652. Scene.prototype.updateTransformMatrix = function (force) {
  22653. if (!this.activeCamera) {
  22654. return;
  22655. }
  22656. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22657. };
  22658. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22659. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22660. };
  22661. Scene.prototype._renderForCamera = function (camera) {
  22662. if (camera && camera._skipRendering) {
  22663. return;
  22664. }
  22665. var engine = this._engine;
  22666. this.activeCamera = camera;
  22667. if (!this.activeCamera)
  22668. throw new Error("Active camera not set");
  22669. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22670. // Viewport
  22671. engine.setViewport(this.activeCamera.viewport);
  22672. // Camera
  22673. this.resetCachedMaterial();
  22674. this._renderId++;
  22675. this.activeCamera.update();
  22676. this.updateTransformMatrix();
  22677. if (camera._alternateCamera) {
  22678. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22679. this._alternateRendering = true;
  22680. }
  22681. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22682. // Meshes
  22683. this._evaluateActiveMeshes();
  22684. // Software skinning
  22685. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22686. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22687. mesh.applySkeleton(mesh.skeleton);
  22688. }
  22689. // Render targets
  22690. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22691. var needsRestoreFrameBuffer = false;
  22692. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22693. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22694. }
  22695. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22696. this._intermediateRendering = true;
  22697. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22698. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22699. var renderTarget = this._renderTargets.data[renderIndex];
  22700. if (renderTarget._shouldRender()) {
  22701. this._renderId++;
  22702. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22703. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22704. }
  22705. }
  22706. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22707. this._intermediateRendering = false;
  22708. this._renderId++;
  22709. needsRestoreFrameBuffer = true; // Restore back buffer
  22710. }
  22711. // Render HighlightLayer Texture
  22712. var stencilState = this._engine.getStencilBuffer();
  22713. var renderhighlights = false;
  22714. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22715. this._intermediateRendering = true;
  22716. for (var i = 0; i < this.highlightLayers.length; i++) {
  22717. var highlightLayer = this.highlightLayers[i];
  22718. if (highlightLayer.shouldRender() &&
  22719. (!highlightLayer.camera ||
  22720. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22721. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22722. renderhighlights = true;
  22723. var renderTarget = highlightLayer._mainTexture;
  22724. if (renderTarget._shouldRender()) {
  22725. this._renderId++;
  22726. renderTarget.render(false, false);
  22727. needsRestoreFrameBuffer = true;
  22728. }
  22729. }
  22730. }
  22731. this._intermediateRendering = false;
  22732. this._renderId++;
  22733. }
  22734. if (needsRestoreFrameBuffer) {
  22735. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22736. }
  22737. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22738. // Prepare Frame
  22739. this.postProcessManager._prepareFrame();
  22740. // Backgrounds
  22741. var layerIndex;
  22742. var layer;
  22743. if (this.layers.length) {
  22744. engine.setDepthBuffer(false);
  22745. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22746. layer = this.layers[layerIndex];
  22747. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22748. layer.render();
  22749. }
  22750. }
  22751. engine.setDepthBuffer(true);
  22752. }
  22753. // Activate HighlightLayer stencil
  22754. if (renderhighlights) {
  22755. this._engine.setStencilBuffer(true);
  22756. }
  22757. // Render
  22758. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22759. this._renderingManager.render(null, null, true, true);
  22760. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22761. // Restore HighlightLayer stencil
  22762. if (renderhighlights) {
  22763. this._engine.setStencilBuffer(stencilState);
  22764. }
  22765. // Bounding boxes
  22766. if (this._boundingBoxRenderer) {
  22767. this._boundingBoxRenderer.render();
  22768. }
  22769. // Lens flares
  22770. if (this.lensFlaresEnabled) {
  22771. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22772. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22773. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22774. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22775. lensFlareSystem.render();
  22776. }
  22777. }
  22778. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22779. }
  22780. // Foregrounds
  22781. if (this.layers.length) {
  22782. engine.setDepthBuffer(false);
  22783. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22784. layer = this.layers[layerIndex];
  22785. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22786. layer.render();
  22787. }
  22788. }
  22789. engine.setDepthBuffer(true);
  22790. }
  22791. // Highlight Layer
  22792. if (renderhighlights) {
  22793. engine.setDepthBuffer(false);
  22794. for (var i = 0; i < this.highlightLayers.length; i++) {
  22795. if (this.highlightLayers[i].shouldRender()) {
  22796. this.highlightLayers[i].render();
  22797. }
  22798. }
  22799. engine.setDepthBuffer(true);
  22800. }
  22801. // Finalize frame
  22802. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22803. // Reset some special arrays
  22804. this._renderTargets.reset();
  22805. this._alternateRendering = false;
  22806. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22807. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22808. };
  22809. Scene.prototype._processSubCameras = function (camera) {
  22810. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22811. this._renderForCamera(camera);
  22812. return;
  22813. }
  22814. // Update camera
  22815. if (this.activeCamera) {
  22816. this.activeCamera.update();
  22817. }
  22818. // rig cameras
  22819. for (var index = 0; index < camera._rigCameras.length; index++) {
  22820. this._renderForCamera(camera._rigCameras[index]);
  22821. }
  22822. this.activeCamera = camera;
  22823. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22824. };
  22825. Scene.prototype._checkIntersections = function () {
  22826. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22827. var sourceMesh = this._meshesForIntersections.data[index];
  22828. if (!sourceMesh.actionManager) {
  22829. continue;
  22830. }
  22831. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22832. var action = sourceMesh.actionManager.actions[actionIndex];
  22833. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22834. var parameters = action.getTriggerParameter();
  22835. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22836. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22837. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22838. if (areIntersecting && currentIntersectionInProgress === -1) {
  22839. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22840. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22841. sourceMesh._intersectionsInProgress.push(otherMesh);
  22842. }
  22843. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22844. sourceMesh._intersectionsInProgress.push(otherMesh);
  22845. }
  22846. }
  22847. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22848. //They intersected, and now they don't.
  22849. //is this trigger an exit trigger? execute an event.
  22850. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22851. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22852. }
  22853. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22854. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22855. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22856. }
  22857. }
  22858. }
  22859. }
  22860. }
  22861. };
  22862. Scene.prototype.render = function () {
  22863. if (this.isDisposed) {
  22864. return;
  22865. }
  22866. this._activeParticles.fetchNewFrame();
  22867. this._totalVertices.fetchNewFrame();
  22868. this._activeIndices.fetchNewFrame();
  22869. this._activeBones.fetchNewFrame();
  22870. this._meshesForIntersections.reset();
  22871. this.resetCachedMaterial();
  22872. this.onBeforeAnimationsObservable.notifyObservers(this);
  22873. // Actions
  22874. if (this.actionManager) {
  22875. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22876. }
  22877. //Simplification Queue
  22878. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22879. this.simplificationQueue.executeNext();
  22880. }
  22881. if (this._engine.isDeterministicLockStep()) {
  22882. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22883. var defaultFPS = (60.0 / 1000.0);
  22884. var defaultFrameTime = 1000 / 60; // frame time in MS
  22885. if (this._physicsEngine) {
  22886. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22887. }
  22888. var stepsTaken = 0;
  22889. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22890. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22891. internalSteps = Math.min(internalSteps, maxSubSteps);
  22892. do {
  22893. this.onBeforeStepObservable.notifyObservers(this);
  22894. // Animations
  22895. this._animationRatio = defaultFrameTime * defaultFPS;
  22896. this._animate();
  22897. this.onAfterAnimationsObservable.notifyObservers(this);
  22898. // Physics
  22899. if (this._physicsEngine) {
  22900. this.onBeforePhysicsObservable.notifyObservers(this);
  22901. this._physicsEngine._step(defaultFrameTime / 1000);
  22902. this.onAfterPhysicsObservable.notifyObservers(this);
  22903. }
  22904. this.onAfterStepObservable.notifyObservers(this);
  22905. this._currentStepId++;
  22906. stepsTaken++;
  22907. deltaTime -= defaultFrameTime;
  22908. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22909. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22910. }
  22911. else {
  22912. // Animations
  22913. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22914. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22915. this._animate();
  22916. this.onAfterAnimationsObservable.notifyObservers(this);
  22917. // Physics
  22918. if (this._physicsEngine) {
  22919. this.onBeforePhysicsObservable.notifyObservers(this);
  22920. this._physicsEngine._step(deltaTime / 1000.0);
  22921. this.onAfterPhysicsObservable.notifyObservers(this);
  22922. }
  22923. }
  22924. // update gamepad manager
  22925. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22926. this._gamepadManager._checkGamepadsStatus();
  22927. }
  22928. // Before render
  22929. this.onBeforeRenderObservable.notifyObservers(this);
  22930. // Customs render targets
  22931. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22932. var engine = this.getEngine();
  22933. var currentActiveCamera = this.activeCamera;
  22934. if (this.renderTargetsEnabled) {
  22935. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22936. this._intermediateRendering = true;
  22937. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22938. var renderTarget = this.customRenderTargets[customIndex];
  22939. if (renderTarget._shouldRender()) {
  22940. this._renderId++;
  22941. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22942. if (!this.activeCamera)
  22943. throw new Error("Active camera not set");
  22944. // Viewport
  22945. engine.setViewport(this.activeCamera.viewport);
  22946. // Camera
  22947. this.updateTransformMatrix();
  22948. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22949. }
  22950. }
  22951. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22952. this._intermediateRendering = false;
  22953. this._renderId++;
  22954. }
  22955. // Restore back buffer
  22956. if (this.customRenderTargets.length > 0) {
  22957. engine.restoreDefaultFramebuffer();
  22958. }
  22959. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22960. this.activeCamera = currentActiveCamera;
  22961. // Procedural textures
  22962. if (this.proceduralTexturesEnabled) {
  22963. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22964. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22965. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22966. if (proceduralTexture._shouldRender()) {
  22967. proceduralTexture.render();
  22968. }
  22969. }
  22970. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22971. }
  22972. // Clear
  22973. if (this.autoClearDepthAndStencil || this.autoClear) {
  22974. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22975. }
  22976. // Shadows
  22977. if (this.shadowsEnabled) {
  22978. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22979. var light = this.lights[lightIndex];
  22980. var shadowGenerator = light.getShadowGenerator();
  22981. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22982. var shadowMap = (shadowGenerator.getShadowMap());
  22983. if (this.textures.indexOf(shadowMap) !== -1) {
  22984. this._renderTargets.push(shadowMap);
  22985. }
  22986. }
  22987. }
  22988. }
  22989. // Depth renderer
  22990. if (this._depthRenderer) {
  22991. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22992. }
  22993. // Geometry renderer
  22994. if (this._geometryBufferRenderer) {
  22995. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22996. }
  22997. // RenderPipeline
  22998. if (this._postProcessRenderPipelineManager) {
  22999. this._postProcessRenderPipelineManager.update();
  23000. }
  23001. // Multi-cameras?
  23002. if (this.activeCameras.length > 0) {
  23003. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23004. if (cameraIndex > 0) {
  23005. this._engine.clear(null, false, true, true);
  23006. }
  23007. this._processSubCameras(this.activeCameras[cameraIndex]);
  23008. }
  23009. }
  23010. else {
  23011. if (!this.activeCamera) {
  23012. throw new Error("No camera defined");
  23013. }
  23014. this._processSubCameras(this.activeCamera);
  23015. }
  23016. // Intersection checks
  23017. this._checkIntersections();
  23018. // Update the audio listener attached to the camera
  23019. if (BABYLON.AudioEngine) {
  23020. this._updateAudioParameters();
  23021. }
  23022. // After render
  23023. if (this.afterRender) {
  23024. this.afterRender();
  23025. }
  23026. this.onAfterRenderObservable.notifyObservers(this);
  23027. // Cleaning
  23028. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23029. var data = this._toBeDisposed.data[index];
  23030. if (data) {
  23031. data.dispose();
  23032. }
  23033. this._toBeDisposed[index] = null;
  23034. }
  23035. this._toBeDisposed.reset();
  23036. if (this.dumpNextRenderTargets) {
  23037. this.dumpNextRenderTargets = false;
  23038. }
  23039. this._activeBones.addCount(0, true);
  23040. this._activeIndices.addCount(0, true);
  23041. this._activeParticles.addCount(0, true);
  23042. };
  23043. Scene.prototype._updateAudioParameters = function () {
  23044. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23045. return;
  23046. }
  23047. var listeningCamera;
  23048. var audioEngine = BABYLON.Engine.audioEngine;
  23049. if (this.activeCameras.length > 0) {
  23050. listeningCamera = this.activeCameras[0];
  23051. }
  23052. else {
  23053. listeningCamera = this.activeCamera;
  23054. }
  23055. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23056. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23057. // for VR cameras
  23058. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23059. listeningCamera = listeningCamera.rigCameras[0];
  23060. }
  23061. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23062. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23063. cameraDirection.normalize();
  23064. // To avoid some errors on GearVR
  23065. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23066. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23067. }
  23068. var i;
  23069. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23070. var sound = this.mainSoundTrack.soundCollection[i];
  23071. if (sound.useCustomAttenuation) {
  23072. sound.updateDistanceFromListener();
  23073. }
  23074. }
  23075. for (i = 0; i < this.soundTracks.length; i++) {
  23076. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23077. sound = this.soundTracks[i].soundCollection[j];
  23078. if (sound.useCustomAttenuation) {
  23079. sound.updateDistanceFromListener();
  23080. }
  23081. }
  23082. }
  23083. }
  23084. };
  23085. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23086. // Audio
  23087. get: function () {
  23088. return this._audioEnabled;
  23089. },
  23090. set: function (value) {
  23091. this._audioEnabled = value;
  23092. if (BABYLON.AudioEngine) {
  23093. if (this._audioEnabled) {
  23094. this._enableAudio();
  23095. }
  23096. else {
  23097. this._disableAudio();
  23098. }
  23099. }
  23100. },
  23101. enumerable: true,
  23102. configurable: true
  23103. });
  23104. Scene.prototype._disableAudio = function () {
  23105. var i;
  23106. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23107. this.mainSoundTrack.soundCollection[i].pause();
  23108. }
  23109. for (i = 0; i < this.soundTracks.length; i++) {
  23110. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23111. this.soundTracks[i].soundCollection[j].pause();
  23112. }
  23113. }
  23114. };
  23115. Scene.prototype._enableAudio = function () {
  23116. var i;
  23117. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23118. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23119. this.mainSoundTrack.soundCollection[i].play();
  23120. }
  23121. }
  23122. for (i = 0; i < this.soundTracks.length; i++) {
  23123. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23124. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23125. this.soundTracks[i].soundCollection[j].play();
  23126. }
  23127. }
  23128. }
  23129. };
  23130. Object.defineProperty(Scene.prototype, "headphone", {
  23131. get: function () {
  23132. return this._headphone;
  23133. },
  23134. set: function (value) {
  23135. this._headphone = value;
  23136. if (BABYLON.AudioEngine) {
  23137. if (this._headphone) {
  23138. this._switchAudioModeForHeadphones();
  23139. }
  23140. else {
  23141. this._switchAudioModeForNormalSpeakers();
  23142. }
  23143. }
  23144. },
  23145. enumerable: true,
  23146. configurable: true
  23147. });
  23148. Scene.prototype._switchAudioModeForHeadphones = function () {
  23149. this.mainSoundTrack.switchPanningModelToHRTF();
  23150. for (var i = 0; i < this.soundTracks.length; i++) {
  23151. this.soundTracks[i].switchPanningModelToHRTF();
  23152. }
  23153. };
  23154. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23155. this.mainSoundTrack.switchPanningModelToEqualPower();
  23156. for (var i = 0; i < this.soundTracks.length; i++) {
  23157. this.soundTracks[i].switchPanningModelToEqualPower();
  23158. }
  23159. };
  23160. Scene.prototype.enableDepthRenderer = function () {
  23161. if (this._depthRenderer) {
  23162. return this._depthRenderer;
  23163. }
  23164. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23165. return this._depthRenderer;
  23166. };
  23167. Scene.prototype.disableDepthRenderer = function () {
  23168. if (!this._depthRenderer) {
  23169. return;
  23170. }
  23171. this._depthRenderer.dispose();
  23172. this._depthRenderer = null;
  23173. };
  23174. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23175. if (ratio === void 0) { ratio = 1; }
  23176. if (this._geometryBufferRenderer) {
  23177. return this._geometryBufferRenderer;
  23178. }
  23179. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23180. if (!this._geometryBufferRenderer.isSupported) {
  23181. this._geometryBufferRenderer = null;
  23182. }
  23183. return this._geometryBufferRenderer;
  23184. };
  23185. Scene.prototype.disableGeometryBufferRenderer = function () {
  23186. if (!this._geometryBufferRenderer) {
  23187. return;
  23188. }
  23189. this._geometryBufferRenderer.dispose();
  23190. this._geometryBufferRenderer = null;
  23191. };
  23192. Scene.prototype.freezeMaterials = function () {
  23193. for (var i = 0; i < this.materials.length; i++) {
  23194. this.materials[i].freeze();
  23195. }
  23196. };
  23197. Scene.prototype.unfreezeMaterials = function () {
  23198. for (var i = 0; i < this.materials.length; i++) {
  23199. this.materials[i].unfreeze();
  23200. }
  23201. };
  23202. Scene.prototype.dispose = function () {
  23203. this.beforeRender = null;
  23204. this.afterRender = null;
  23205. this.skeletons = [];
  23206. this.morphTargetManagers = [];
  23207. this.importedMeshesFiles = new Array();
  23208. this.stopAllAnimations();
  23209. this.resetCachedMaterial();
  23210. if (this._depthRenderer) {
  23211. this._depthRenderer.dispose();
  23212. }
  23213. if (this._gamepadManager) {
  23214. this._gamepadManager.dispose();
  23215. this._gamepadManager = null;
  23216. }
  23217. // Smart arrays
  23218. if (this.activeCamera) {
  23219. this.activeCamera._activeMeshes.dispose();
  23220. this.activeCamera = null;
  23221. }
  23222. this._activeMeshes.dispose();
  23223. this._renderingManager.dispose();
  23224. this._processedMaterials.dispose();
  23225. this._activeParticleSystems.dispose();
  23226. this._activeSkeletons.dispose();
  23227. this._softwareSkinnedMeshes.dispose();
  23228. this._renderTargets.dispose();
  23229. if (this._boundingBoxRenderer) {
  23230. this._boundingBoxRenderer.dispose();
  23231. }
  23232. this._meshesForIntersections.dispose();
  23233. this._toBeDisposed.dispose();
  23234. // Abort active requests
  23235. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23236. var request = _a[_i];
  23237. request.abort();
  23238. }
  23239. // Debug layer
  23240. if (this._debugLayer) {
  23241. this._debugLayer.hide();
  23242. }
  23243. // Events
  23244. this.onDisposeObservable.notifyObservers(this);
  23245. this.onDisposeObservable.clear();
  23246. this.onBeforeRenderObservable.clear();
  23247. this.onAfterRenderObservable.clear();
  23248. this.OnBeforeRenderTargetsRenderObservable.clear();
  23249. this.OnAfterRenderTargetsRenderObservable.clear();
  23250. this.onAfterStepObservable.clear();
  23251. this.onBeforeStepObservable.clear();
  23252. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23253. this.onAfterActiveMeshesEvaluationObservable.clear();
  23254. this.onBeforeParticlesRenderingObservable.clear();
  23255. this.onAfterParticlesRenderingObservable.clear();
  23256. this.onBeforeSpritesRenderingObservable.clear();
  23257. this.onAfterSpritesRenderingObservable.clear();
  23258. this.onBeforeDrawPhaseObservable.clear();
  23259. this.onAfterDrawPhaseObservable.clear();
  23260. this.onBeforePhysicsObservable.clear();
  23261. this.onAfterPhysicsObservable.clear();
  23262. this.onBeforeAnimationsObservable.clear();
  23263. this.onAfterAnimationsObservable.clear();
  23264. this.onDataLoadedObservable.clear();
  23265. this.detachControl();
  23266. // Release sounds & sounds tracks
  23267. if (BABYLON.AudioEngine) {
  23268. this.disposeSounds();
  23269. }
  23270. // VR Helper
  23271. if (this.VRHelper) {
  23272. this.VRHelper.dispose();
  23273. }
  23274. // Detach cameras
  23275. var canvas = this._engine.getRenderingCanvas();
  23276. if (canvas) {
  23277. var index;
  23278. for (index = 0; index < this.cameras.length; index++) {
  23279. this.cameras[index].detachControl(canvas);
  23280. }
  23281. }
  23282. // Release animation groups
  23283. while (this.animationGroups.length) {
  23284. this.animationGroups[0].dispose();
  23285. }
  23286. // Release lights
  23287. while (this.lights.length) {
  23288. this.lights[0].dispose();
  23289. }
  23290. // Release meshes
  23291. while (this.meshes.length) {
  23292. this.meshes[0].dispose(true);
  23293. }
  23294. while (this.transformNodes.length) {
  23295. this.removeTransformNode(this.transformNodes[0]);
  23296. }
  23297. // Release cameras
  23298. while (this.cameras.length) {
  23299. this.cameras[0].dispose();
  23300. }
  23301. // Release materials
  23302. if (this.defaultMaterial) {
  23303. this.defaultMaterial.dispose();
  23304. }
  23305. while (this.multiMaterials.length) {
  23306. this.multiMaterials[0].dispose();
  23307. }
  23308. while (this.materials.length) {
  23309. this.materials[0].dispose();
  23310. }
  23311. // Release particles
  23312. while (this.particleSystems.length) {
  23313. this.particleSystems[0].dispose();
  23314. }
  23315. // Release sprites
  23316. while (this.spriteManagers.length) {
  23317. this.spriteManagers[0].dispose();
  23318. }
  23319. // Release postProcesses
  23320. while (this.postProcesses.length) {
  23321. this.postProcesses[0].dispose();
  23322. }
  23323. // Release layers
  23324. while (this.layers.length) {
  23325. this.layers[0].dispose();
  23326. }
  23327. while (this.highlightLayers.length) {
  23328. this.highlightLayers[0].dispose();
  23329. }
  23330. // Release textures
  23331. while (this.textures.length) {
  23332. this.textures[0].dispose();
  23333. }
  23334. // Release UBO
  23335. this._sceneUbo.dispose();
  23336. if (this._alternateSceneUbo) {
  23337. this._alternateSceneUbo.dispose();
  23338. }
  23339. // Post-processes
  23340. this.postProcessManager.dispose();
  23341. if (this._postProcessRenderPipelineManager) {
  23342. this._postProcessRenderPipelineManager.dispose();
  23343. }
  23344. // Physics
  23345. if (this._physicsEngine) {
  23346. this.disablePhysicsEngine();
  23347. }
  23348. // Remove from engine
  23349. index = this._engine.scenes.indexOf(this);
  23350. if (index > -1) {
  23351. this._engine.scenes.splice(index, 1);
  23352. }
  23353. this._engine.wipeCaches(true);
  23354. this._isDisposed = true;
  23355. };
  23356. Object.defineProperty(Scene.prototype, "isDisposed", {
  23357. get: function () {
  23358. return this._isDisposed;
  23359. },
  23360. enumerable: true,
  23361. configurable: true
  23362. });
  23363. // Release sounds & sounds tracks
  23364. Scene.prototype.disposeSounds = function () {
  23365. if (!this._mainSoundTrack) {
  23366. return;
  23367. }
  23368. this.mainSoundTrack.dispose();
  23369. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23370. this.soundTracks[scIndex].dispose();
  23371. }
  23372. };
  23373. // Octrees
  23374. Scene.prototype.getWorldExtends = function () {
  23375. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23376. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23377. for (var index = 0; index < this.meshes.length; index++) {
  23378. var mesh = this.meshes[index];
  23379. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23380. continue;
  23381. }
  23382. mesh.computeWorldMatrix(true);
  23383. var boundingInfo = mesh.getBoundingInfo();
  23384. var minBox = boundingInfo.boundingBox.minimumWorld;
  23385. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23386. BABYLON.Tools.CheckExtends(minBox, min, max);
  23387. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23388. }
  23389. return {
  23390. min: min,
  23391. max: max
  23392. };
  23393. };
  23394. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23395. if (maxCapacity === void 0) { maxCapacity = 64; }
  23396. if (maxDepth === void 0) { maxDepth = 2; }
  23397. if (!this._selectionOctree) {
  23398. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23399. }
  23400. var worldExtends = this.getWorldExtends();
  23401. // Update octree
  23402. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23403. return this._selectionOctree;
  23404. };
  23405. // Picking
  23406. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23407. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23408. var result = BABYLON.Ray.Zero();
  23409. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23410. return result;
  23411. };
  23412. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23413. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23414. var engine = this._engine;
  23415. if (!camera) {
  23416. if (!this.activeCamera)
  23417. throw new Error("Active camera not set");
  23418. camera = this.activeCamera;
  23419. }
  23420. var cameraViewport = camera.viewport;
  23421. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23422. // Moving coordinates to local viewport world
  23423. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23424. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23425. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23426. return this;
  23427. };
  23428. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23429. var result = BABYLON.Ray.Zero();
  23430. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23431. return result;
  23432. };
  23433. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23434. if (!BABYLON.PickingInfo) {
  23435. return this;
  23436. }
  23437. var engine = this._engine;
  23438. if (!camera) {
  23439. if (!this.activeCamera)
  23440. throw new Error("Active camera not set");
  23441. camera = this.activeCamera;
  23442. }
  23443. var cameraViewport = camera.viewport;
  23444. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23445. var identity = BABYLON.Matrix.Identity();
  23446. // Moving coordinates to local viewport world
  23447. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23448. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23449. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23450. return this;
  23451. };
  23452. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23453. if (!BABYLON.PickingInfo) {
  23454. return null;
  23455. }
  23456. var pickingInfo = null;
  23457. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23458. var mesh = this.meshes[meshIndex];
  23459. if (predicate) {
  23460. if (!predicate(mesh)) {
  23461. continue;
  23462. }
  23463. }
  23464. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23465. continue;
  23466. }
  23467. var world = mesh.getWorldMatrix();
  23468. var ray = rayFunction(world);
  23469. var result = mesh.intersects(ray, fastCheck);
  23470. if (!result || !result.hit)
  23471. continue;
  23472. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23473. continue;
  23474. pickingInfo = result;
  23475. if (fastCheck) {
  23476. break;
  23477. }
  23478. }
  23479. return pickingInfo || new BABYLON.PickingInfo();
  23480. };
  23481. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23482. if (!BABYLON.PickingInfo) {
  23483. return null;
  23484. }
  23485. var pickingInfos = new Array();
  23486. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23487. var mesh = this.meshes[meshIndex];
  23488. if (predicate) {
  23489. if (!predicate(mesh)) {
  23490. continue;
  23491. }
  23492. }
  23493. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23494. continue;
  23495. }
  23496. var world = mesh.getWorldMatrix();
  23497. var ray = rayFunction(world);
  23498. var result = mesh.intersects(ray, false);
  23499. if (!result || !result.hit)
  23500. continue;
  23501. pickingInfos.push(result);
  23502. }
  23503. return pickingInfos;
  23504. };
  23505. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23506. if (!BABYLON.PickingInfo) {
  23507. return null;
  23508. }
  23509. var pickingInfo = null;
  23510. if (!camera) {
  23511. if (!this.activeCamera) {
  23512. return null;
  23513. }
  23514. camera = this.activeCamera;
  23515. }
  23516. if (this.spriteManagers.length > 0) {
  23517. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23518. var spriteManager = this.spriteManagers[spriteIndex];
  23519. if (!spriteManager.isPickable) {
  23520. continue;
  23521. }
  23522. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23523. if (!result || !result.hit)
  23524. continue;
  23525. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23526. continue;
  23527. pickingInfo = result;
  23528. if (fastCheck) {
  23529. break;
  23530. }
  23531. }
  23532. }
  23533. return pickingInfo || new BABYLON.PickingInfo();
  23534. };
  23535. /** Launch a ray to try to pick a mesh in the scene
  23536. * @param x position on screen
  23537. * @param y position on screen
  23538. * @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
  23539. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23540. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23541. */
  23542. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23543. var _this = this;
  23544. if (!BABYLON.PickingInfo) {
  23545. return null;
  23546. }
  23547. return this._internalPick(function (world) {
  23548. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23549. return _this._tempPickingRay;
  23550. }, predicate, fastCheck);
  23551. };
  23552. /** Launch a ray to try to pick a sprite in the scene
  23553. * @param x position on screen
  23554. * @param y position on screen
  23555. * @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
  23556. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23557. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23558. */
  23559. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23560. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23561. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23562. };
  23563. /** Use the given ray to pick a mesh in the scene
  23564. * @param ray The ray to use to pick meshes
  23565. * @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
  23566. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23567. */
  23568. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23569. var _this = this;
  23570. return this._internalPick(function (world) {
  23571. if (!_this._pickWithRayInverseMatrix) {
  23572. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23573. }
  23574. world.invertToRef(_this._pickWithRayInverseMatrix);
  23575. if (!_this._cachedRayForTransform) {
  23576. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23577. }
  23578. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23579. return _this._cachedRayForTransform;
  23580. }, predicate, fastCheck);
  23581. };
  23582. /**
  23583. * Launch a ray to try to pick a mesh in the scene
  23584. * @param x X position on screen
  23585. * @param y Y position on screen
  23586. * @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
  23587. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23588. */
  23589. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23590. var _this = this;
  23591. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23592. };
  23593. /**
  23594. * Launch a ray to try to pick a mesh in the scene
  23595. * @param ray Ray to use
  23596. * @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
  23597. */
  23598. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23599. var _this = this;
  23600. return this._internalMultiPick(function (world) {
  23601. if (!_this._pickWithRayInverseMatrix) {
  23602. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23603. }
  23604. world.invertToRef(_this._pickWithRayInverseMatrix);
  23605. if (!_this._cachedRayForTransform) {
  23606. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23607. }
  23608. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23609. return _this._cachedRayForTransform;
  23610. }, predicate);
  23611. };
  23612. Scene.prototype.setPointerOverMesh = function (mesh) {
  23613. if (this._pointerOverMesh === mesh) {
  23614. return;
  23615. }
  23616. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23617. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23618. }
  23619. this._pointerOverMesh = mesh;
  23620. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23621. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23622. }
  23623. };
  23624. Scene.prototype.getPointerOverMesh = function () {
  23625. return this._pointerOverMesh;
  23626. };
  23627. Scene.prototype.setPointerOverSprite = function (sprite) {
  23628. if (this._pointerOverSprite === sprite) {
  23629. return;
  23630. }
  23631. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23632. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23633. }
  23634. this._pointerOverSprite = sprite;
  23635. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23636. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23637. }
  23638. };
  23639. Scene.prototype.getPointerOverSprite = function () {
  23640. return this._pointerOverSprite;
  23641. };
  23642. // Physics
  23643. Scene.prototype.getPhysicsEngine = function () {
  23644. return this._physicsEngine;
  23645. };
  23646. /**
  23647. * Enables physics to the current scene
  23648. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23649. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23650. * @return {boolean} was the physics engine initialized
  23651. */
  23652. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23653. if (gravity === void 0) { gravity = null; }
  23654. if (this._physicsEngine) {
  23655. return true;
  23656. }
  23657. try {
  23658. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23659. return true;
  23660. }
  23661. catch (e) {
  23662. BABYLON.Tools.Error(e.message);
  23663. return false;
  23664. }
  23665. };
  23666. Scene.prototype.disablePhysicsEngine = function () {
  23667. if (!this._physicsEngine) {
  23668. return;
  23669. }
  23670. this._physicsEngine.dispose();
  23671. this._physicsEngine = null;
  23672. };
  23673. Scene.prototype.isPhysicsEnabled = function () {
  23674. return this._physicsEngine !== undefined;
  23675. };
  23676. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23677. var mesh = compound.parts[0].mesh;
  23678. if (mesh.physicsImpostor) {
  23679. mesh.physicsImpostor.dispose();
  23680. mesh.physicsImpostor = null;
  23681. }
  23682. };
  23683. // Misc.
  23684. Scene.prototype._rebuildGeometries = function () {
  23685. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23686. var geometry = _a[_i];
  23687. geometry._rebuild();
  23688. }
  23689. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23690. var mesh = _c[_b];
  23691. mesh._rebuild();
  23692. }
  23693. if (this.postProcessManager) {
  23694. this.postProcessManager._rebuild();
  23695. }
  23696. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23697. var layer = _e[_d];
  23698. layer._rebuild();
  23699. }
  23700. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23701. var highlightLayer = _g[_f];
  23702. highlightLayer._rebuild();
  23703. }
  23704. if (this._boundingBoxRenderer) {
  23705. this._boundingBoxRenderer._rebuild();
  23706. }
  23707. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23708. var system = _j[_h];
  23709. system.rebuild();
  23710. }
  23711. if (this._postProcessRenderPipelineManager) {
  23712. this._postProcessRenderPipelineManager._rebuild();
  23713. }
  23714. };
  23715. Scene.prototype._rebuildTextures = function () {
  23716. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23717. var texture = _a[_i];
  23718. texture._rebuild();
  23719. }
  23720. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23721. };
  23722. /**
  23723. * Creates a default light for the scene.
  23724. * @param replace Whether to replace the existing lights in the scene.
  23725. */
  23726. Scene.prototype.createDefaultLight = function (replace) {
  23727. if (replace === void 0) { replace = false; }
  23728. // Dispose existing light in replace mode.
  23729. if (replace) {
  23730. if (this.lights) {
  23731. for (var i = 0; i < this.lights.length; i++) {
  23732. this.lights[i].dispose();
  23733. }
  23734. }
  23735. }
  23736. // Light
  23737. if (this.lights.length === 0) {
  23738. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23739. }
  23740. };
  23741. /**
  23742. * Creates a default camera for the scene.
  23743. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  23744. * @param replace Whether to replace the existing active camera in the scene.
  23745. * @param attachCameraControls Whether to attach camera controls to the canvas.
  23746. */
  23747. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  23748. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23749. if (replace === void 0) { replace = false; }
  23750. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23751. // Dispose existing camera in replace mode.
  23752. if (replace) {
  23753. if (this.activeCamera) {
  23754. this.activeCamera.dispose();
  23755. this.activeCamera = null;
  23756. }
  23757. }
  23758. // Camera
  23759. if (!this.activeCamera) {
  23760. var worldExtends = this.getWorldExtends();
  23761. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23762. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23763. var camera;
  23764. var radius = worldSize.length() * 1.5;
  23765. if (createArcRotateCamera) {
  23766. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23767. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23768. arcRotateCamera.wheelPrecision = 100 / radius;
  23769. camera = arcRotateCamera;
  23770. }
  23771. else {
  23772. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23773. freeCamera.setTarget(worldCenter);
  23774. camera = freeCamera;
  23775. }
  23776. camera.minZ = radius * 0.01;
  23777. camera.maxZ = radius * 1000;
  23778. camera.speed = radius * 0.2;
  23779. this.activeCamera = camera;
  23780. var canvas = this.getEngine().getRenderingCanvas();
  23781. if (attachCameraControls && canvas) {
  23782. camera.attachControl(canvas);
  23783. }
  23784. }
  23785. };
  23786. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23787. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23788. if (replace === void 0) { replace = false; }
  23789. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23790. this.createDefaultLight(replace);
  23791. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  23792. };
  23793. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23794. if (pbr === void 0) { pbr = false; }
  23795. if (scale === void 0) { scale = 1000; }
  23796. if (blur === void 0) { blur = 0; }
  23797. if (environmentTexture) {
  23798. this.environmentTexture = environmentTexture;
  23799. }
  23800. if (!this.environmentTexture) {
  23801. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23802. return null;
  23803. }
  23804. // Skybox
  23805. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23806. if (pbr) {
  23807. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23808. hdrSkyboxMaterial.backFaceCulling = false;
  23809. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23810. if (hdrSkyboxMaterial.reflectionTexture) {
  23811. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23812. }
  23813. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23814. hdrSkyboxMaterial.disableLighting = true;
  23815. hdrSkyboxMaterial.twoSidedLighting = true;
  23816. hdrSkybox.infiniteDistance = true;
  23817. hdrSkybox.material = hdrSkyboxMaterial;
  23818. }
  23819. else {
  23820. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23821. skyboxMaterial.backFaceCulling = false;
  23822. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23823. if (skyboxMaterial.reflectionTexture) {
  23824. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23825. }
  23826. skyboxMaterial.disableLighting = true;
  23827. hdrSkybox.infiniteDistance = true;
  23828. hdrSkybox.material = skyboxMaterial;
  23829. }
  23830. return hdrSkybox;
  23831. };
  23832. Scene.prototype.createDefaultEnvironment = function (options) {
  23833. if (BABYLON.EnvironmentHelper) {
  23834. return new BABYLON.EnvironmentHelper(options, this);
  23835. }
  23836. return null;
  23837. };
  23838. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23839. if (webVROptions === void 0) { webVROptions = {}; }
  23840. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23841. };
  23842. // Tags
  23843. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23844. if (tagsQuery === undefined) {
  23845. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23846. return list;
  23847. }
  23848. var listByTags = [];
  23849. forEach = forEach || (function (item) { return; });
  23850. for (var i in list) {
  23851. var item = list[i];
  23852. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23853. listByTags.push(item);
  23854. forEach(item);
  23855. }
  23856. }
  23857. return listByTags;
  23858. };
  23859. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23860. return this._getByTags(this.meshes, tagsQuery, forEach);
  23861. };
  23862. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23863. return this._getByTags(this.cameras, tagsQuery, forEach);
  23864. };
  23865. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23866. return this._getByTags(this.lights, tagsQuery, forEach);
  23867. };
  23868. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23869. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23870. };
  23871. /**
  23872. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23873. * This allowed control for front to back rendering or reversly depending of the special needs.
  23874. *
  23875. * @param renderingGroupId The rendering group id corresponding to its index
  23876. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23877. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23878. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23879. */
  23880. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23881. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23882. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23883. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23884. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23885. };
  23886. /**
  23887. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23888. *
  23889. * @param renderingGroupId The rendering group id corresponding to its index
  23890. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23891. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23892. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23893. */
  23894. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23895. if (depth === void 0) { depth = true; }
  23896. if (stencil === void 0) { stencil = true; }
  23897. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23898. };
  23899. /**
  23900. * Will flag all materials as dirty to trigger new shader compilation
  23901. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23902. */
  23903. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23904. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23905. var material = _a[_i];
  23906. if (predicate && !predicate(material)) {
  23907. continue;
  23908. }
  23909. material.markAsDirty(flag);
  23910. }
  23911. };
  23912. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23913. var _this = this;
  23914. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23915. this._activeRequests.push(request);
  23916. request.onCompleteObservable.add(function (request) {
  23917. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23918. });
  23919. return request;
  23920. };
  23921. /** @ignore */
  23922. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23923. var _this = this;
  23924. return new Promise(function (resolve, reject) {
  23925. _this._loadFile(url, function (data) {
  23926. resolve(data);
  23927. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23928. reject(exception);
  23929. });
  23930. });
  23931. };
  23932. // Statics
  23933. Scene._FOGMODE_NONE = 0;
  23934. Scene._FOGMODE_EXP = 1;
  23935. Scene._FOGMODE_EXP2 = 2;
  23936. Scene._FOGMODE_LINEAR = 3;
  23937. Scene._uniqueIdCounter = 0;
  23938. Scene.MinDeltaTime = 1.0;
  23939. Scene.MaxDeltaTime = 1000.0;
  23940. /** The distance in pixel that you have to move to prevent some events */
  23941. Scene.DragMovementThreshold = 10; // in pixels
  23942. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23943. Scene.LongPressDelay = 500; // in milliseconds
  23944. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23945. Scene.DoubleClickDelay = 300; // in milliseconds
  23946. /** If you need to check double click without raising a single click at first click, enable this flag */
  23947. Scene.ExclusiveDoubleClickMode = false;
  23948. return Scene;
  23949. }());
  23950. BABYLON.Scene = Scene;
  23951. })(BABYLON || (BABYLON = {}));
  23952. //# sourceMappingURL=babylon.scene.js.map
  23953. var BABYLON;
  23954. (function (BABYLON) {
  23955. /**
  23956. * Set of assets to keep when moving a scene into an asset container.
  23957. */
  23958. var KeepAssets = /** @class */ (function () {
  23959. function KeepAssets() {
  23960. /**
  23961. * Cameras to keep.
  23962. */
  23963. this.cameras = new Array();
  23964. /**
  23965. * Lights to keep.
  23966. */
  23967. this.lights = new Array();
  23968. /**
  23969. * Meshes to keep.
  23970. */
  23971. this.meshes = new Array();
  23972. /**
  23973. * Skeletons to keep.
  23974. */
  23975. this.skeletons = new Array();
  23976. /**
  23977. * ParticleSystems to keep.
  23978. */
  23979. this.particleSystems = new Array();
  23980. /**
  23981. * Animations to keep.
  23982. */
  23983. this.animations = new Array();
  23984. /**
  23985. * MultiMaterials to keep.
  23986. */
  23987. this.multiMaterials = new Array();
  23988. /**
  23989. * Materials to keep.
  23990. */
  23991. this.materials = new Array();
  23992. /**
  23993. * MorphTargetManagers to keep.
  23994. */
  23995. this.morphTargetManagers = new Array();
  23996. /**
  23997. * Geometries to keep.
  23998. */
  23999. this.geometries = new Array();
  24000. /**
  24001. * TransformNodes to keep.
  24002. */
  24003. this.transformNodes = new Array();
  24004. /**
  24005. * LensFlareSystems to keep.
  24006. */
  24007. this.lensFlareSystems = new Array();
  24008. /**
  24009. * ShadowGenerators to keep.
  24010. */
  24011. this.shadowGenerators = new Array();
  24012. /**
  24013. * ActionManagers to keep.
  24014. */
  24015. this.actionManagers = new Array();
  24016. /**
  24017. * Sounds to keep.
  24018. */
  24019. this.sounds = new Array();
  24020. }
  24021. return KeepAssets;
  24022. }());
  24023. BABYLON.KeepAssets = KeepAssets;
  24024. /**
  24025. * Container with a set of assets that can be added or removed from a scene.
  24026. */
  24027. var AssetContainer = /** @class */ (function () {
  24028. /**
  24029. * Instantiates an AssetContainer.
  24030. * @param scene The scene the AssetContainer belongs to.
  24031. */
  24032. function AssetContainer(scene) {
  24033. // Objects
  24034. /**
  24035. * Cameras populated in the container.
  24036. */
  24037. this.cameras = new Array();
  24038. /**
  24039. * Lights populated in the container.
  24040. */
  24041. this.lights = new Array();
  24042. /**
  24043. * Meshes populated in the container.
  24044. */
  24045. this.meshes = new Array();
  24046. /**
  24047. * Skeletons populated in the container.
  24048. */
  24049. this.skeletons = new Array();
  24050. /**
  24051. * ParticleSystems populated in the container.
  24052. */
  24053. this.particleSystems = new Array();
  24054. /**
  24055. * Animations populated in the container.
  24056. */
  24057. this.animations = new Array();
  24058. /**
  24059. * MultiMaterials populated in the container.
  24060. */
  24061. this.multiMaterials = new Array();
  24062. /**
  24063. * Materials populated in the container.
  24064. */
  24065. this.materials = new Array();
  24066. /**
  24067. * MorphTargetManagers populated in the container.
  24068. */
  24069. this.morphTargetManagers = new Array();
  24070. /**
  24071. * Geometries populated in the container.
  24072. */
  24073. this.geometries = new Array();
  24074. /**
  24075. * TransformNodes populated in the container.
  24076. */
  24077. this.transformNodes = new Array();
  24078. /**
  24079. * LensFlareSystems populated in the container.
  24080. */
  24081. this.lensFlareSystems = new Array();
  24082. /**
  24083. * ShadowGenerators populated in the container.
  24084. */
  24085. this.shadowGenerators = new Array();
  24086. /**
  24087. * ActionManagers populated in the container.
  24088. */
  24089. this.actionManagers = new Array();
  24090. /**
  24091. * Sounds populated in the container.
  24092. */
  24093. this.sounds = new Array();
  24094. this.scene = scene;
  24095. }
  24096. /**
  24097. * Adds all the assets from the container to the scene.
  24098. */
  24099. AssetContainer.prototype.addAllToScene = function () {
  24100. var _this = this;
  24101. this.cameras.forEach(function (o) {
  24102. _this.scene.addCamera(o);
  24103. });
  24104. this.lights.forEach(function (o) {
  24105. _this.scene.addLight(o);
  24106. });
  24107. this.meshes.forEach(function (o) {
  24108. _this.scene.addMesh(o);
  24109. });
  24110. this.skeletons.forEach(function (o) {
  24111. _this.scene.addSkeleton(o);
  24112. });
  24113. this.particleSystems.forEach(function (o) {
  24114. _this.scene.addParticleSystem(o);
  24115. });
  24116. this.animations.forEach(function (o) {
  24117. _this.scene.addAnimation(o);
  24118. });
  24119. this.multiMaterials.forEach(function (o) {
  24120. _this.scene.addMultiMaterial(o);
  24121. });
  24122. this.materials.forEach(function (o) {
  24123. _this.scene.addMaterial(o);
  24124. });
  24125. this.morphTargetManagers.forEach(function (o) {
  24126. _this.scene.addMorphTargetManager(o);
  24127. });
  24128. this.geometries.forEach(function (o) {
  24129. _this.scene.addGeometry(o);
  24130. });
  24131. this.transformNodes.forEach(function (o) {
  24132. _this.scene.addTransformNode(o);
  24133. });
  24134. this.lensFlareSystems.forEach(function (o) {
  24135. _this.scene.addLensFlareSystem(o);
  24136. });
  24137. this.actionManagers.forEach(function (o) {
  24138. _this.scene.addActionManager(o);
  24139. });
  24140. this.sounds.forEach(function (o) {
  24141. o.play();
  24142. o.autoplay = true;
  24143. _this.scene.mainSoundTrack.AddSound(o);
  24144. });
  24145. };
  24146. /**
  24147. * Removes all the assets in the container from the scene
  24148. */
  24149. AssetContainer.prototype.removeAllFromScene = function () {
  24150. var _this = this;
  24151. this.cameras.forEach(function (o) {
  24152. _this.scene.removeCamera(o);
  24153. });
  24154. this.lights.forEach(function (o) {
  24155. _this.scene.removeLight(o);
  24156. });
  24157. this.meshes.forEach(function (o) {
  24158. _this.scene.removeMesh(o);
  24159. });
  24160. this.skeletons.forEach(function (o) {
  24161. _this.scene.removeSkeleton(o);
  24162. });
  24163. this.particleSystems.forEach(function (o) {
  24164. _this.scene.removeParticleSystem(o);
  24165. });
  24166. this.animations.forEach(function (o) {
  24167. _this.scene.removeAnimation(o);
  24168. });
  24169. this.multiMaterials.forEach(function (o) {
  24170. _this.scene.removeMultiMaterial(o);
  24171. });
  24172. this.materials.forEach(function (o) {
  24173. _this.scene.removeMaterial(o);
  24174. });
  24175. this.morphTargetManagers.forEach(function (o) {
  24176. _this.scene.removeMorphTargetManager(o);
  24177. });
  24178. this.geometries.forEach(function (o) {
  24179. _this.scene.removeGeometry(o);
  24180. });
  24181. this.transformNodes.forEach(function (o) {
  24182. _this.scene.removeTransformNode(o);
  24183. });
  24184. this.lensFlareSystems.forEach(function (o) {
  24185. _this.scene.removeLensFlareSystem(o);
  24186. });
  24187. this.actionManagers.forEach(function (o) {
  24188. _this.scene.removeActionManager(o);
  24189. });
  24190. this.sounds.forEach(function (o) {
  24191. o.stop();
  24192. o.autoplay = false;
  24193. _this.scene.mainSoundTrack.RemoveSound(o);
  24194. });
  24195. };
  24196. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24197. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24198. var asset = sourceAssets_1[_i];
  24199. var move = true;
  24200. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24201. var keepAsset = keepAssets_1[_a];
  24202. if (asset === keepAsset) {
  24203. move = false;
  24204. break;
  24205. }
  24206. }
  24207. if (move) {
  24208. targetAssets.push(asset);
  24209. }
  24210. }
  24211. };
  24212. /**
  24213. * Removes all the assets contained in the scene and adds them to the container.
  24214. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24215. */
  24216. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24217. if (keepAssets === undefined) {
  24218. keepAssets = new KeepAssets();
  24219. }
  24220. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24221. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24222. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24223. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24224. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24225. Array.prototype.push.apply(this.animations, this.scene.animations);
  24226. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24227. Array.prototype.push.apply(this.lights, this.scene.lights);
  24228. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24229. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24230. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24231. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24232. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24233. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24234. this.removeAllFromScene();
  24235. };
  24236. return AssetContainer;
  24237. }());
  24238. BABYLON.AssetContainer = AssetContainer;
  24239. })(BABYLON || (BABYLON = {}));
  24240. //# sourceMappingURL=babylon.assetContainer.js.map
  24241. var BABYLON;
  24242. (function (BABYLON) {
  24243. var Buffer = /** @class */ (function () {
  24244. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24245. if (instanced === void 0) { instanced = false; }
  24246. if (engine instanceof BABYLON.Mesh) {
  24247. this._engine = engine.getScene().getEngine();
  24248. }
  24249. else {
  24250. this._engine = engine;
  24251. }
  24252. this._updatable = updatable;
  24253. this._data = data;
  24254. this._strideSize = stride;
  24255. if (!postponeInternalCreation) {
  24256. this.create();
  24257. }
  24258. this._instanced = instanced;
  24259. this._instanceDivisor = instanced ? 1 : 0;
  24260. }
  24261. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24262. // a lot of these parameters are ignored as they are overriden by the buffer
  24263. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24264. };
  24265. // Properties
  24266. Buffer.prototype.isUpdatable = function () {
  24267. return this._updatable;
  24268. };
  24269. Buffer.prototype.getData = function () {
  24270. return this._data;
  24271. };
  24272. Buffer.prototype.getBuffer = function () {
  24273. return this._buffer;
  24274. };
  24275. Buffer.prototype.getStrideSize = function () {
  24276. return this._strideSize;
  24277. };
  24278. Buffer.prototype.getIsInstanced = function () {
  24279. return this._instanced;
  24280. };
  24281. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24282. get: function () {
  24283. return this._instanceDivisor;
  24284. },
  24285. set: function (value) {
  24286. this._instanceDivisor = value;
  24287. if (value == 0) {
  24288. this._instanced = false;
  24289. }
  24290. else {
  24291. this._instanced = true;
  24292. }
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. // Methods
  24298. Buffer.prototype.create = function (data) {
  24299. if (data === void 0) { data = null; }
  24300. if (!data && this._buffer) {
  24301. return; // nothing to do
  24302. }
  24303. data = data || this._data;
  24304. if (!data) {
  24305. return;
  24306. }
  24307. if (!this._buffer) {
  24308. if (this._updatable) {
  24309. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24310. this._data = data;
  24311. }
  24312. else {
  24313. this._buffer = this._engine.createVertexBuffer(data);
  24314. }
  24315. }
  24316. else if (this._updatable) {
  24317. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24318. this._data = data;
  24319. }
  24320. };
  24321. Buffer.prototype._rebuild = function () {
  24322. this._buffer = null;
  24323. this.create(this._data);
  24324. };
  24325. Buffer.prototype.update = function (data) {
  24326. this.create(data);
  24327. };
  24328. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24329. if (!this._buffer) {
  24330. return;
  24331. }
  24332. if (this._updatable) {
  24333. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24334. this._data = null;
  24335. }
  24336. };
  24337. Buffer.prototype.dispose = function () {
  24338. if (!this._buffer) {
  24339. return;
  24340. }
  24341. if (this._engine._releaseBuffer(this._buffer)) {
  24342. this._buffer = null;
  24343. }
  24344. };
  24345. return Buffer;
  24346. }());
  24347. BABYLON.Buffer = Buffer;
  24348. })(BABYLON || (BABYLON = {}));
  24349. //# sourceMappingURL=babylon.buffer.js.map
  24350. var BABYLON;
  24351. (function (BABYLON) {
  24352. var VertexBuffer = /** @class */ (function () {
  24353. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24354. if (!stride) {
  24355. // Deduce stride from kind
  24356. switch (kind) {
  24357. case VertexBuffer.PositionKind:
  24358. stride = 3;
  24359. break;
  24360. case VertexBuffer.NormalKind:
  24361. stride = 3;
  24362. break;
  24363. case VertexBuffer.UVKind:
  24364. case VertexBuffer.UV2Kind:
  24365. case VertexBuffer.UV3Kind:
  24366. case VertexBuffer.UV4Kind:
  24367. case VertexBuffer.UV5Kind:
  24368. case VertexBuffer.UV6Kind:
  24369. stride = 2;
  24370. break;
  24371. case VertexBuffer.TangentKind:
  24372. case VertexBuffer.ColorKind:
  24373. stride = 4;
  24374. break;
  24375. case VertexBuffer.MatricesIndicesKind:
  24376. case VertexBuffer.MatricesIndicesExtraKind:
  24377. stride = 4;
  24378. break;
  24379. case VertexBuffer.MatricesWeightsKind:
  24380. case VertexBuffer.MatricesWeightsExtraKind:
  24381. default:
  24382. stride = 4;
  24383. break;
  24384. }
  24385. }
  24386. if (data instanceof BABYLON.Buffer) {
  24387. if (!stride) {
  24388. stride = data.getStrideSize();
  24389. }
  24390. this._buffer = data;
  24391. this._ownsBuffer = false;
  24392. }
  24393. else {
  24394. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24395. this._ownsBuffer = true;
  24396. }
  24397. this._stride = stride;
  24398. this._offset = offset ? offset : 0;
  24399. this._size = size ? size : stride;
  24400. this._kind = kind;
  24401. }
  24402. VertexBuffer.prototype._rebuild = function () {
  24403. if (!this._buffer) {
  24404. return;
  24405. }
  24406. this._buffer._rebuild();
  24407. };
  24408. /**
  24409. * Returns the kind of the VertexBuffer (string).
  24410. */
  24411. VertexBuffer.prototype.getKind = function () {
  24412. return this._kind;
  24413. };
  24414. // Properties
  24415. /**
  24416. * Boolean : is the VertexBuffer updatable ?
  24417. */
  24418. VertexBuffer.prototype.isUpdatable = function () {
  24419. return this._buffer.isUpdatable();
  24420. };
  24421. /**
  24422. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24423. */
  24424. VertexBuffer.prototype.getData = function () {
  24425. return this._buffer.getData();
  24426. };
  24427. /**
  24428. * Returns the WebGLBuffer associated to the VertexBuffer.
  24429. */
  24430. VertexBuffer.prototype.getBuffer = function () {
  24431. return this._buffer.getBuffer();
  24432. };
  24433. /**
  24434. * Returns the stride of the VertexBuffer (integer).
  24435. */
  24436. VertexBuffer.prototype.getStrideSize = function () {
  24437. return this._stride;
  24438. };
  24439. /**
  24440. * Returns the offset (integer).
  24441. */
  24442. VertexBuffer.prototype.getOffset = function () {
  24443. return this._offset;
  24444. };
  24445. /**
  24446. * Returns the VertexBuffer total size (integer).
  24447. */
  24448. VertexBuffer.prototype.getSize = function () {
  24449. return this._size;
  24450. };
  24451. /**
  24452. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24453. */
  24454. VertexBuffer.prototype.getIsInstanced = function () {
  24455. return this._buffer.getIsInstanced();
  24456. };
  24457. /**
  24458. * Returns the instancing divisor, zero for non-instanced (integer).
  24459. */
  24460. VertexBuffer.prototype.getInstanceDivisor = function () {
  24461. return this._buffer.instanceDivisor;
  24462. };
  24463. // Methods
  24464. /**
  24465. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24466. * Returns the created WebGLBuffer.
  24467. */
  24468. VertexBuffer.prototype.create = function (data) {
  24469. return this._buffer.create(data);
  24470. };
  24471. /**
  24472. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24473. * This function will create a new buffer if the current one is not updatable
  24474. * Returns the updated WebGLBuffer.
  24475. */
  24476. VertexBuffer.prototype.update = function (data) {
  24477. return this._buffer.update(data);
  24478. };
  24479. /**
  24480. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24481. * Returns the directly updated WebGLBuffer.
  24482. */
  24483. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24484. return this._buffer.updateDirectly(data, offset);
  24485. };
  24486. /**
  24487. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24488. */
  24489. VertexBuffer.prototype.dispose = function () {
  24490. if (this._ownsBuffer) {
  24491. this._buffer.dispose();
  24492. }
  24493. };
  24494. Object.defineProperty(VertexBuffer, "PositionKind", {
  24495. get: function () {
  24496. return VertexBuffer._PositionKind;
  24497. },
  24498. enumerable: true,
  24499. configurable: true
  24500. });
  24501. Object.defineProperty(VertexBuffer, "NormalKind", {
  24502. get: function () {
  24503. return VertexBuffer._NormalKind;
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Object.defineProperty(VertexBuffer, "TangentKind", {
  24509. get: function () {
  24510. return VertexBuffer._TangentKind;
  24511. },
  24512. enumerable: true,
  24513. configurable: true
  24514. });
  24515. Object.defineProperty(VertexBuffer, "UVKind", {
  24516. get: function () {
  24517. return VertexBuffer._UVKind;
  24518. },
  24519. enumerable: true,
  24520. configurable: true
  24521. });
  24522. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24523. get: function () {
  24524. return VertexBuffer._UV2Kind;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24530. get: function () {
  24531. return VertexBuffer._UV3Kind;
  24532. },
  24533. enumerable: true,
  24534. configurable: true
  24535. });
  24536. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24537. get: function () {
  24538. return VertexBuffer._UV4Kind;
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24544. get: function () {
  24545. return VertexBuffer._UV5Kind;
  24546. },
  24547. enumerable: true,
  24548. configurable: true
  24549. });
  24550. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24551. get: function () {
  24552. return VertexBuffer._UV6Kind;
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(VertexBuffer, "ColorKind", {
  24558. get: function () {
  24559. return VertexBuffer._ColorKind;
  24560. },
  24561. enumerable: true,
  24562. configurable: true
  24563. });
  24564. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24565. get: function () {
  24566. return VertexBuffer._MatricesIndicesKind;
  24567. },
  24568. enumerable: true,
  24569. configurable: true
  24570. });
  24571. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24572. get: function () {
  24573. return VertexBuffer._MatricesWeightsKind;
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24579. get: function () {
  24580. return VertexBuffer._MatricesIndicesExtraKind;
  24581. },
  24582. enumerable: true,
  24583. configurable: true
  24584. });
  24585. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24586. get: function () {
  24587. return VertexBuffer._MatricesWeightsExtraKind;
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. // Enums
  24593. VertexBuffer._PositionKind = "position";
  24594. VertexBuffer._NormalKind = "normal";
  24595. VertexBuffer._TangentKind = "tangent";
  24596. VertexBuffer._UVKind = "uv";
  24597. VertexBuffer._UV2Kind = "uv2";
  24598. VertexBuffer._UV3Kind = "uv3";
  24599. VertexBuffer._UV4Kind = "uv4";
  24600. VertexBuffer._UV5Kind = "uv5";
  24601. VertexBuffer._UV6Kind = "uv6";
  24602. VertexBuffer._ColorKind = "color";
  24603. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24604. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24605. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24606. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24607. return VertexBuffer;
  24608. }());
  24609. BABYLON.VertexBuffer = VertexBuffer;
  24610. })(BABYLON || (BABYLON = {}));
  24611. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24612. var BABYLON;
  24613. (function (BABYLON) {
  24614. /**
  24615. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24616. */
  24617. var DummyInternalTextureTracker = /** @class */ (function () {
  24618. function DummyInternalTextureTracker() {
  24619. /**
  24620. * Gets or set the previous tracker in the list
  24621. */
  24622. this.previous = null;
  24623. /**
  24624. * Gets or set the next tracker in the list
  24625. */
  24626. this.next = null;
  24627. }
  24628. return DummyInternalTextureTracker;
  24629. }());
  24630. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24631. })(BABYLON || (BABYLON = {}));
  24632. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24633. var BABYLON;
  24634. (function (BABYLON) {
  24635. /**
  24636. * Class used to store data associated with WebGL texture data for the engine
  24637. * This class should not be used directly
  24638. */
  24639. var InternalTexture = /** @class */ (function () {
  24640. /**
  24641. * Creates a new InternalTexture
  24642. * @param engine defines the engine to use
  24643. * @param dataSource defines the type of data that will be used
  24644. */
  24645. function InternalTexture(engine, dataSource) {
  24646. /**
  24647. * Observable called when the texture is loaded
  24648. */
  24649. this.onLoadedObservable = new BABYLON.Observable();
  24650. /**
  24651. * Gets or set the previous tracker in the list
  24652. */
  24653. this.previous = null;
  24654. /**
  24655. * Gets or set the next tracker in the list
  24656. */
  24657. this.next = null;
  24658. // Private
  24659. /** @ignore */
  24660. this._initialSlot = -1;
  24661. /** @ignore */
  24662. this._designatedSlot = -1;
  24663. /** @ignore */
  24664. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24665. /** @ignore */
  24666. this._references = 1;
  24667. this._engine = engine;
  24668. this._dataSource = dataSource;
  24669. this._webGLTexture = engine._createTexture();
  24670. }
  24671. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24672. /**
  24673. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24674. */
  24675. get: function () {
  24676. return this._dataSource;
  24677. },
  24678. enumerable: true,
  24679. configurable: true
  24680. });
  24681. /**
  24682. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24683. */
  24684. InternalTexture.prototype.incrementReferences = function () {
  24685. this._references++;
  24686. };
  24687. /**
  24688. * Change the size of the texture (not the size of the content)
  24689. * @param width defines the new width
  24690. * @param height defines the new height
  24691. * @param depth defines the new depth (1 by default)
  24692. */
  24693. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24694. if (depth === void 0) { depth = 1; }
  24695. this.width = width;
  24696. this.height = height;
  24697. this.depth = depth;
  24698. this.baseWidth = width;
  24699. this.baseHeight = height;
  24700. this.baseDepth = depth;
  24701. this._size = width * height * depth;
  24702. };
  24703. /** @ignore */
  24704. InternalTexture.prototype._rebuild = function () {
  24705. var _this = this;
  24706. var proxy;
  24707. this.isReady = false;
  24708. this._cachedCoordinatesMode = null;
  24709. this._cachedWrapU = null;
  24710. this._cachedWrapV = null;
  24711. this._cachedAnisotropicFilteringLevel = null;
  24712. switch (this._dataSource) {
  24713. case InternalTexture.DATASOURCE_TEMP:
  24714. return;
  24715. case InternalTexture.DATASOURCE_URL:
  24716. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24717. _this.isReady = true;
  24718. }, null, this._buffer, undefined, this.format);
  24719. proxy._swapAndDie(this);
  24720. return;
  24721. case InternalTexture.DATASOURCE_RAW:
  24722. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24723. proxy._swapAndDie(this);
  24724. this.isReady = true;
  24725. return;
  24726. case InternalTexture.DATASOURCE_RAW3D:
  24727. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24728. proxy._swapAndDie(this);
  24729. this.isReady = true;
  24730. return;
  24731. case InternalTexture.DATASOURCE_DYNAMIC:
  24732. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24733. proxy._swapAndDie(this);
  24734. // The engine will make sure to update content so no need to flag it as isReady = true
  24735. return;
  24736. case InternalTexture.DATASOURCE_RENDERTARGET:
  24737. var options = new BABYLON.RenderTargetCreationOptions();
  24738. options.generateDepthBuffer = this._generateDepthBuffer;
  24739. options.generateMipMaps = this.generateMipMaps;
  24740. options.generateStencilBuffer = this._generateStencilBuffer;
  24741. options.samplingMode = this.samplingMode;
  24742. options.type = this.type;
  24743. if (this.isCube) {
  24744. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24745. }
  24746. else {
  24747. var size = {
  24748. width: this.width,
  24749. height: this.height
  24750. };
  24751. proxy = this._engine.createRenderTargetTexture(size, options);
  24752. }
  24753. proxy._swapAndDie(this);
  24754. this.isReady = true;
  24755. return;
  24756. case InternalTexture.DATASOURCE_CUBE:
  24757. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24758. _this.isReady = true;
  24759. }, null, this.format, this._extension);
  24760. proxy._swapAndDie(this);
  24761. return;
  24762. case InternalTexture.DATASOURCE_CUBERAW:
  24763. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24764. proxy._swapAndDie(this);
  24765. this.isReady = true;
  24766. return;
  24767. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24768. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24769. if (proxy) {
  24770. proxy._swapAndDie(_this);
  24771. }
  24772. _this.isReady = true;
  24773. }, null, this.format, this._extension);
  24774. return;
  24775. }
  24776. };
  24777. InternalTexture.prototype._swapAndDie = function (target) {
  24778. target._webGLTexture = this._webGLTexture;
  24779. if (this._framebuffer) {
  24780. target._framebuffer = this._framebuffer;
  24781. }
  24782. if (this._depthStencilBuffer) {
  24783. target._depthStencilBuffer = this._depthStencilBuffer;
  24784. }
  24785. if (this._lodTextureHigh) {
  24786. if (target._lodTextureHigh) {
  24787. target._lodTextureHigh.dispose();
  24788. }
  24789. target._lodTextureHigh = this._lodTextureHigh;
  24790. }
  24791. if (this._lodTextureMid) {
  24792. if (target._lodTextureMid) {
  24793. target._lodTextureMid.dispose();
  24794. }
  24795. target._lodTextureMid = this._lodTextureMid;
  24796. }
  24797. if (this._lodTextureLow) {
  24798. if (target._lodTextureLow) {
  24799. target._lodTextureLow.dispose();
  24800. }
  24801. target._lodTextureLow = this._lodTextureLow;
  24802. }
  24803. var cache = this._engine.getLoadedTexturesCache();
  24804. var index = cache.indexOf(this);
  24805. if (index !== -1) {
  24806. cache.splice(index, 1);
  24807. }
  24808. };
  24809. /**
  24810. * Dispose the current allocated resources
  24811. */
  24812. InternalTexture.prototype.dispose = function () {
  24813. if (!this._webGLTexture) {
  24814. return;
  24815. }
  24816. this._references--;
  24817. if (this._references === 0) {
  24818. this._engine._releaseTexture(this);
  24819. this._webGLTexture = null;
  24820. this.previous = null;
  24821. this.next = null;
  24822. }
  24823. };
  24824. /**
  24825. * The source of the texture data is unknown
  24826. */
  24827. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24828. /**
  24829. * Texture data comes from an URL
  24830. */
  24831. InternalTexture.DATASOURCE_URL = 1;
  24832. /**
  24833. * Texture data is only used for temporary storage
  24834. */
  24835. InternalTexture.DATASOURCE_TEMP = 2;
  24836. /**
  24837. * Texture data comes from raw data (ArrayBuffer)
  24838. */
  24839. InternalTexture.DATASOURCE_RAW = 3;
  24840. /**
  24841. * Texture content is dynamic (video or dynamic texture)
  24842. */
  24843. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24844. /**
  24845. * Texture content is generated by rendering to it
  24846. */
  24847. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24848. /**
  24849. * Texture content is part of a multi render target process
  24850. */
  24851. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24852. /**
  24853. * Texture data comes from a cube data file
  24854. */
  24855. InternalTexture.DATASOURCE_CUBE = 7;
  24856. /**
  24857. * Texture data comes from a raw cube data
  24858. */
  24859. InternalTexture.DATASOURCE_CUBERAW = 8;
  24860. /**
  24861. * Texture data come from a prefiltered cube data file
  24862. */
  24863. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24864. /**
  24865. * Texture content is raw 3D data
  24866. */
  24867. InternalTexture.DATASOURCE_RAW3D = 10;
  24868. return InternalTexture;
  24869. }());
  24870. BABYLON.InternalTexture = InternalTexture;
  24871. })(BABYLON || (BABYLON = {}));
  24872. //# sourceMappingURL=babylon.internalTexture.js.map
  24873. var BABYLON;
  24874. (function (BABYLON) {
  24875. var BaseTexture = /** @class */ (function () {
  24876. function BaseTexture(scene) {
  24877. this._hasAlpha = false;
  24878. this.getAlphaFromRGB = false;
  24879. this.level = 1;
  24880. this.coordinatesIndex = 0;
  24881. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24882. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24883. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24884. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24885. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24886. this.isCube = false;
  24887. this.is3D = false;
  24888. this.gammaSpace = true;
  24889. this.invertZ = false;
  24890. this.lodLevelInAlpha = false;
  24891. this.lodGenerationOffset = 0.0;
  24892. this.lodGenerationScale = 0.8;
  24893. this.isRenderTarget = false;
  24894. this.animations = new Array();
  24895. /**
  24896. * An event triggered when the texture is disposed.
  24897. * @type {BABYLON.Observable}
  24898. */
  24899. this.onDisposeObservable = new BABYLON.Observable();
  24900. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24901. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24902. if (this._scene) {
  24903. this._scene.textures.push(this);
  24904. }
  24905. this._uid = null;
  24906. }
  24907. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24908. get: function () {
  24909. return this._hasAlpha;
  24910. },
  24911. set: function (value) {
  24912. if (this._hasAlpha === value) {
  24913. return;
  24914. }
  24915. this._hasAlpha = value;
  24916. if (this._scene) {
  24917. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  24918. }
  24919. },
  24920. enumerable: true,
  24921. configurable: true
  24922. });
  24923. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24924. get: function () {
  24925. return this._coordinatesMode;
  24926. },
  24927. set: function (value) {
  24928. if (this._coordinatesMode === value) {
  24929. return;
  24930. }
  24931. this._coordinatesMode = value;
  24932. if (this._scene) {
  24933. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24934. }
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. Object.defineProperty(BaseTexture.prototype, "uid", {
  24940. get: function () {
  24941. if (!this._uid) {
  24942. this._uid = BABYLON.Tools.RandomId();
  24943. }
  24944. return this._uid;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. BaseTexture.prototype.toString = function () {
  24950. return this.name;
  24951. };
  24952. BaseTexture.prototype.getClassName = function () {
  24953. return "BaseTexture";
  24954. };
  24955. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24956. set: function (callback) {
  24957. if (this._onDisposeObserver) {
  24958. this.onDisposeObservable.remove(this._onDisposeObserver);
  24959. }
  24960. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24961. },
  24962. enumerable: true,
  24963. configurable: true
  24964. });
  24965. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24966. get: function () {
  24967. return true;
  24968. },
  24969. enumerable: true,
  24970. configurable: true
  24971. });
  24972. BaseTexture.prototype.getScene = function () {
  24973. return this._scene;
  24974. };
  24975. BaseTexture.prototype.getTextureMatrix = function () {
  24976. return BABYLON.Matrix.IdentityReadOnly;
  24977. };
  24978. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24979. return BABYLON.Matrix.IdentityReadOnly;
  24980. };
  24981. BaseTexture.prototype.getInternalTexture = function () {
  24982. return this._texture;
  24983. };
  24984. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24985. return !this.isBlocking || this.isReady();
  24986. };
  24987. BaseTexture.prototype.isReady = function () {
  24988. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24989. this.delayLoad();
  24990. return false;
  24991. }
  24992. if (this._texture) {
  24993. return this._texture.isReady;
  24994. }
  24995. return false;
  24996. };
  24997. BaseTexture.prototype.getSize = function () {
  24998. if (this._texture && this._texture.width) {
  24999. return new BABYLON.Size(this._texture.width, this._texture.height);
  25000. }
  25001. if (this._texture && this._texture._size) {
  25002. return new BABYLON.Size(this._texture._size, this._texture._size);
  25003. }
  25004. return BABYLON.Size.Zero();
  25005. };
  25006. BaseTexture.prototype.getBaseSize = function () {
  25007. if (!this.isReady() || !this._texture)
  25008. return BABYLON.Size.Zero();
  25009. if (this._texture._size) {
  25010. return new BABYLON.Size(this._texture._size, this._texture._size);
  25011. }
  25012. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25013. };
  25014. BaseTexture.prototype.scale = function (ratio) {
  25015. };
  25016. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25017. get: function () {
  25018. return false;
  25019. },
  25020. enumerable: true,
  25021. configurable: true
  25022. });
  25023. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25024. if (!this._scene) {
  25025. return null;
  25026. }
  25027. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25028. for (var index = 0; index < texturesCache.length; index++) {
  25029. var texturesCacheEntry = texturesCache[index];
  25030. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25031. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25032. texturesCacheEntry.incrementReferences();
  25033. return texturesCacheEntry;
  25034. }
  25035. }
  25036. }
  25037. return null;
  25038. };
  25039. BaseTexture.prototype._rebuild = function () {
  25040. };
  25041. BaseTexture.prototype.delayLoad = function () {
  25042. };
  25043. BaseTexture.prototype.clone = function () {
  25044. return null;
  25045. };
  25046. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25047. get: function () {
  25048. if (!this._texture) {
  25049. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25050. }
  25051. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25052. },
  25053. enumerable: true,
  25054. configurable: true
  25055. });
  25056. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25057. get: function () {
  25058. if (!this._texture) {
  25059. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25060. }
  25061. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25062. },
  25063. enumerable: true,
  25064. configurable: true
  25065. });
  25066. BaseTexture.prototype.readPixels = function (faceIndex) {
  25067. if (faceIndex === void 0) { faceIndex = 0; }
  25068. if (!this._texture) {
  25069. return null;
  25070. }
  25071. var size = this.getSize();
  25072. var scene = this.getScene();
  25073. if (!scene) {
  25074. return null;
  25075. }
  25076. var engine = scene.getEngine();
  25077. if (this._texture.isCube) {
  25078. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25079. }
  25080. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25081. };
  25082. BaseTexture.prototype.releaseInternalTexture = function () {
  25083. if (this._texture) {
  25084. this._texture.dispose();
  25085. this._texture = null;
  25086. }
  25087. };
  25088. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25089. get: function () {
  25090. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25091. return null;
  25092. }
  25093. if (!this._texture._sphericalPolynomial) {
  25094. this._texture._sphericalPolynomial =
  25095. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25096. }
  25097. return this._texture._sphericalPolynomial;
  25098. },
  25099. set: function (value) {
  25100. if (this._texture) {
  25101. this._texture._sphericalPolynomial = value;
  25102. }
  25103. },
  25104. enumerable: true,
  25105. configurable: true
  25106. });
  25107. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25108. get: function () {
  25109. if (this._texture) {
  25110. return this._texture._lodTextureHigh;
  25111. }
  25112. return null;
  25113. },
  25114. enumerable: true,
  25115. configurable: true
  25116. });
  25117. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25118. get: function () {
  25119. if (this._texture) {
  25120. return this._texture._lodTextureMid;
  25121. }
  25122. return null;
  25123. },
  25124. enumerable: true,
  25125. configurable: true
  25126. });
  25127. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25128. get: function () {
  25129. if (this._texture) {
  25130. return this._texture._lodTextureLow;
  25131. }
  25132. return null;
  25133. },
  25134. enumerable: true,
  25135. configurable: true
  25136. });
  25137. BaseTexture.prototype.dispose = function () {
  25138. if (!this._scene) {
  25139. return;
  25140. }
  25141. // Animations
  25142. this._scene.stopAnimation(this);
  25143. // Remove from scene
  25144. this._scene._removePendingData(this);
  25145. var index = this._scene.textures.indexOf(this);
  25146. if (index >= 0) {
  25147. this._scene.textures.splice(index, 1);
  25148. }
  25149. if (this._texture === undefined) {
  25150. return;
  25151. }
  25152. // Release
  25153. this.releaseInternalTexture();
  25154. // Callback
  25155. this.onDisposeObservable.notifyObservers(this);
  25156. this.onDisposeObservable.clear();
  25157. };
  25158. BaseTexture.prototype.serialize = function () {
  25159. if (!this.name) {
  25160. return null;
  25161. }
  25162. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25163. // Animations
  25164. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25165. return serializationObject;
  25166. };
  25167. BaseTexture.WhenAllReady = function (textures, callback) {
  25168. var numRemaining = textures.length;
  25169. if (numRemaining === 0) {
  25170. callback();
  25171. return;
  25172. }
  25173. var _loop_1 = function () {
  25174. texture = textures[i];
  25175. if (texture.isReady()) {
  25176. if (--numRemaining === 0) {
  25177. callback();
  25178. }
  25179. }
  25180. else {
  25181. onLoadObservable = texture.onLoadObservable;
  25182. var onLoadCallback_1 = function () {
  25183. onLoadObservable.removeCallback(onLoadCallback_1);
  25184. if (--numRemaining === 0) {
  25185. callback();
  25186. }
  25187. };
  25188. onLoadObservable.add(onLoadCallback_1);
  25189. }
  25190. };
  25191. var texture, onLoadObservable;
  25192. for (var i = 0; i < textures.length; i++) {
  25193. _loop_1();
  25194. }
  25195. };
  25196. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25197. __decorate([
  25198. BABYLON.serialize()
  25199. ], BaseTexture.prototype, "name", void 0);
  25200. __decorate([
  25201. BABYLON.serialize("hasAlpha")
  25202. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25203. __decorate([
  25204. BABYLON.serialize()
  25205. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25206. __decorate([
  25207. BABYLON.serialize()
  25208. ], BaseTexture.prototype, "level", void 0);
  25209. __decorate([
  25210. BABYLON.serialize()
  25211. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25212. __decorate([
  25213. BABYLON.serialize("coordinatesMode")
  25214. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25215. __decorate([
  25216. BABYLON.serialize()
  25217. ], BaseTexture.prototype, "wrapU", void 0);
  25218. __decorate([
  25219. BABYLON.serialize()
  25220. ], BaseTexture.prototype, "wrapV", void 0);
  25221. __decorate([
  25222. BABYLON.serialize()
  25223. ], BaseTexture.prototype, "wrapR", void 0);
  25224. __decorate([
  25225. BABYLON.serialize()
  25226. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25227. __decorate([
  25228. BABYLON.serialize()
  25229. ], BaseTexture.prototype, "isCube", void 0);
  25230. __decorate([
  25231. BABYLON.serialize()
  25232. ], BaseTexture.prototype, "is3D", void 0);
  25233. __decorate([
  25234. BABYLON.serialize()
  25235. ], BaseTexture.prototype, "gammaSpace", void 0);
  25236. __decorate([
  25237. BABYLON.serialize()
  25238. ], BaseTexture.prototype, "invertZ", void 0);
  25239. __decorate([
  25240. BABYLON.serialize()
  25241. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25242. __decorate([
  25243. BABYLON.serialize()
  25244. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25245. __decorate([
  25246. BABYLON.serialize()
  25247. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25248. __decorate([
  25249. BABYLON.serialize()
  25250. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25251. return BaseTexture;
  25252. }());
  25253. BABYLON.BaseTexture = BaseTexture;
  25254. })(BABYLON || (BABYLON = {}));
  25255. //# sourceMappingURL=babylon.baseTexture.js.map
  25256. var BABYLON;
  25257. (function (BABYLON) {
  25258. var Texture = /** @class */ (function (_super) {
  25259. __extends(Texture, _super);
  25260. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25261. if (noMipmap === void 0) { noMipmap = false; }
  25262. if (invertY === void 0) { invertY = true; }
  25263. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25264. if (onLoad === void 0) { onLoad = null; }
  25265. if (onError === void 0) { onError = null; }
  25266. if (buffer === void 0) { buffer = null; }
  25267. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25268. var _this = _super.call(this, scene) || this;
  25269. _this.uOffset = 0;
  25270. _this.vOffset = 0;
  25271. _this.uScale = 1.0;
  25272. _this.vScale = 1.0;
  25273. _this.uAng = 0;
  25274. _this.vAng = 0;
  25275. _this.wAng = 0;
  25276. _this._isBlocking = true;
  25277. _this.name = url || "";
  25278. _this.url = url;
  25279. _this._noMipmap = noMipmap;
  25280. _this._invertY = invertY;
  25281. _this._samplingMode = samplingMode;
  25282. _this._buffer = buffer;
  25283. _this._deleteBuffer = deleteBuffer;
  25284. if (format) {
  25285. _this._format = format;
  25286. }
  25287. scene = _this.getScene();
  25288. if (!scene) {
  25289. return _this;
  25290. }
  25291. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25292. var load = function () {
  25293. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25294. _this.onLoadObservable.notifyObservers(_this);
  25295. }
  25296. if (onLoad) {
  25297. onLoad();
  25298. }
  25299. if (!_this.isBlocking && scene) {
  25300. scene.resetCachedMaterial();
  25301. }
  25302. };
  25303. if (!_this.url) {
  25304. _this._delayedOnLoad = load;
  25305. _this._delayedOnError = onError;
  25306. return _this;
  25307. }
  25308. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25309. if (!_this._texture) {
  25310. if (!scene.useDelayedTextureLoading) {
  25311. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25312. if (deleteBuffer) {
  25313. delete _this._buffer;
  25314. }
  25315. }
  25316. else {
  25317. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25318. _this._delayedOnLoad = load;
  25319. _this._delayedOnError = onError;
  25320. }
  25321. }
  25322. else {
  25323. if (_this._texture.isReady) {
  25324. BABYLON.Tools.SetImmediate(function () { return load(); });
  25325. }
  25326. else {
  25327. _this._texture.onLoadedObservable.add(load);
  25328. }
  25329. }
  25330. return _this;
  25331. }
  25332. Object.defineProperty(Texture.prototype, "noMipmap", {
  25333. get: function () {
  25334. return this._noMipmap;
  25335. },
  25336. enumerable: true,
  25337. configurable: true
  25338. });
  25339. Object.defineProperty(Texture.prototype, "isBlocking", {
  25340. get: function () {
  25341. return this._isBlocking;
  25342. },
  25343. set: function (value) {
  25344. this._isBlocking = value;
  25345. },
  25346. enumerable: true,
  25347. configurable: true
  25348. });
  25349. Object.defineProperty(Texture.prototype, "samplingMode", {
  25350. get: function () {
  25351. return this._samplingMode;
  25352. },
  25353. enumerable: true,
  25354. configurable: true
  25355. });
  25356. Texture.prototype.updateURL = function (url) {
  25357. this.url = url;
  25358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25359. this.delayLoad();
  25360. };
  25361. Texture.prototype.delayLoad = function () {
  25362. var _this = this;
  25363. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25364. return;
  25365. }
  25366. var scene = this.getScene();
  25367. if (!scene) {
  25368. return;
  25369. }
  25370. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25371. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25372. if (!this._texture) {
  25373. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25374. if (this._deleteBuffer) {
  25375. delete this._buffer;
  25376. }
  25377. }
  25378. else {
  25379. if (this._texture.isReady) {
  25380. BABYLON.Tools.SetImmediate(function () {
  25381. if (!_this._delayedOnLoad) {
  25382. return;
  25383. }
  25384. _this._delayedOnLoad();
  25385. });
  25386. }
  25387. else {
  25388. if (this._delayedOnLoad) {
  25389. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25390. }
  25391. }
  25392. }
  25393. };
  25394. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25395. if (!this._texture) {
  25396. return;
  25397. }
  25398. var scene = this.getScene();
  25399. if (!scene) {
  25400. return;
  25401. }
  25402. this._samplingMode = samplingMode;
  25403. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25404. };
  25405. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25406. x *= this.uScale;
  25407. y *= this.vScale;
  25408. x -= 0.5 * this.uScale;
  25409. y -= 0.5 * this.vScale;
  25410. z -= 0.5;
  25411. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25412. t.x += 0.5 * this.uScale + this.uOffset;
  25413. t.y += 0.5 * this.vScale + this.vOffset;
  25414. t.z += 0.5;
  25415. };
  25416. Texture.prototype.getTextureMatrix = function () {
  25417. var _this = this;
  25418. if (this.uOffset === this._cachedUOffset &&
  25419. this.vOffset === this._cachedVOffset &&
  25420. this.uScale === this._cachedUScale &&
  25421. this.vScale === this._cachedVScale &&
  25422. this.uAng === this._cachedUAng &&
  25423. this.vAng === this._cachedVAng &&
  25424. this.wAng === this._cachedWAng) {
  25425. return this._cachedTextureMatrix;
  25426. }
  25427. this._cachedUOffset = this.uOffset;
  25428. this._cachedVOffset = this.vOffset;
  25429. this._cachedUScale = this.uScale;
  25430. this._cachedVScale = this.vScale;
  25431. this._cachedUAng = this.uAng;
  25432. this._cachedVAng = this.vAng;
  25433. this._cachedWAng = this.wAng;
  25434. if (!this._cachedTextureMatrix) {
  25435. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25436. this._rowGenerationMatrix = new BABYLON.Matrix();
  25437. this._t0 = BABYLON.Vector3.Zero();
  25438. this._t1 = BABYLON.Vector3.Zero();
  25439. this._t2 = BABYLON.Vector3.Zero();
  25440. }
  25441. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25442. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25443. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25444. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25445. this._t1.subtractInPlace(this._t0);
  25446. this._t2.subtractInPlace(this._t0);
  25447. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25448. this._cachedTextureMatrix.m[0] = this._t1.x;
  25449. this._cachedTextureMatrix.m[1] = this._t1.y;
  25450. this._cachedTextureMatrix.m[2] = this._t1.z;
  25451. this._cachedTextureMatrix.m[4] = this._t2.x;
  25452. this._cachedTextureMatrix.m[5] = this._t2.y;
  25453. this._cachedTextureMatrix.m[6] = this._t2.z;
  25454. this._cachedTextureMatrix.m[8] = this._t0.x;
  25455. this._cachedTextureMatrix.m[9] = this._t0.y;
  25456. this._cachedTextureMatrix.m[10] = this._t0.z;
  25457. var scene = this.getScene();
  25458. if (!scene) {
  25459. return this._cachedTextureMatrix;
  25460. }
  25461. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25462. return mat.hasTexture(_this);
  25463. });
  25464. return this._cachedTextureMatrix;
  25465. };
  25466. Texture.prototype.getReflectionTextureMatrix = function () {
  25467. var _this = this;
  25468. var scene = this.getScene();
  25469. if (!scene) {
  25470. return this._cachedTextureMatrix;
  25471. }
  25472. if (this.uOffset === this._cachedUOffset &&
  25473. this.vOffset === this._cachedVOffset &&
  25474. this.uScale === this._cachedUScale &&
  25475. this.vScale === this._cachedVScale &&
  25476. this.coordinatesMode === this._cachedCoordinatesMode) {
  25477. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25478. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25479. return this._cachedTextureMatrix;
  25480. }
  25481. }
  25482. else {
  25483. return this._cachedTextureMatrix;
  25484. }
  25485. }
  25486. if (!this._cachedTextureMatrix) {
  25487. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25488. }
  25489. if (!this._projectionModeMatrix) {
  25490. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25491. }
  25492. this._cachedUOffset = this.uOffset;
  25493. this._cachedVOffset = this.vOffset;
  25494. this._cachedUScale = this.uScale;
  25495. this._cachedVScale = this.vScale;
  25496. this._cachedCoordinatesMode = this.coordinatesMode;
  25497. switch (this.coordinatesMode) {
  25498. case Texture.PLANAR_MODE:
  25499. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25500. this._cachedTextureMatrix[0] = this.uScale;
  25501. this._cachedTextureMatrix[5] = this.vScale;
  25502. this._cachedTextureMatrix[12] = this.uOffset;
  25503. this._cachedTextureMatrix[13] = this.vOffset;
  25504. break;
  25505. case Texture.PROJECTION_MODE:
  25506. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25507. this._projectionModeMatrix.m[0] = 0.5;
  25508. this._projectionModeMatrix.m[5] = -0.5;
  25509. this._projectionModeMatrix.m[10] = 0.0;
  25510. this._projectionModeMatrix.m[12] = 0.5;
  25511. this._projectionModeMatrix.m[13] = 0.5;
  25512. this._projectionModeMatrix.m[14] = 1.0;
  25513. this._projectionModeMatrix.m[15] = 1.0;
  25514. var projectionMatrix = scene.getProjectionMatrix();
  25515. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25516. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25517. break;
  25518. default:
  25519. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25520. break;
  25521. }
  25522. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25523. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25524. });
  25525. return this._cachedTextureMatrix;
  25526. };
  25527. Texture.prototype.clone = function () {
  25528. var _this = this;
  25529. return BABYLON.SerializationHelper.Clone(function () {
  25530. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25531. }, this);
  25532. };
  25533. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25534. get: function () {
  25535. if (!this._onLoadObservable) {
  25536. this._onLoadObservable = new BABYLON.Observable();
  25537. }
  25538. return this._onLoadObservable;
  25539. },
  25540. enumerable: true,
  25541. configurable: true
  25542. });
  25543. Texture.prototype.serialize = function () {
  25544. var serializationObject = _super.prototype.serialize.call(this);
  25545. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25546. serializationObject.base64String = this._buffer;
  25547. serializationObject.name = serializationObject.name.replace("data:", "");
  25548. }
  25549. return serializationObject;
  25550. };
  25551. Texture.prototype.getClassName = function () {
  25552. return "Texture";
  25553. };
  25554. Texture.prototype.dispose = function () {
  25555. _super.prototype.dispose.call(this);
  25556. if (this.onLoadObservable) {
  25557. this.onLoadObservable.clear();
  25558. this._onLoadObservable = null;
  25559. }
  25560. this._delayedOnLoad = null;
  25561. this._delayedOnError = null;
  25562. };
  25563. // Statics
  25564. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25565. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25566. if (onLoad === void 0) { onLoad = null; }
  25567. if (onError === void 0) { onError = null; }
  25568. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25569. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25570. };
  25571. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25572. if (parsedTexture.customType) {
  25573. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25574. // Update Sampling Mode
  25575. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25576. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25577. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25578. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25579. }
  25580. }
  25581. return parsedCustomTexture;
  25582. }
  25583. if (parsedTexture.isCube) {
  25584. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25585. }
  25586. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25587. return null;
  25588. }
  25589. var texture = BABYLON.SerializationHelper.Parse(function () {
  25590. var generateMipMaps = true;
  25591. if (parsedTexture.noMipmap) {
  25592. generateMipMaps = false;
  25593. }
  25594. if (parsedTexture.mirrorPlane) {
  25595. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25596. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25597. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25598. return mirrorTexture;
  25599. }
  25600. else if (parsedTexture.isRenderTarget) {
  25601. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25602. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25603. return renderTargetTexture;
  25604. }
  25605. else {
  25606. var texture;
  25607. if (parsedTexture.base64String) {
  25608. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25609. }
  25610. else {
  25611. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25612. }
  25613. return texture;
  25614. }
  25615. }, parsedTexture, scene);
  25616. // Update Sampling Mode
  25617. if (parsedTexture.samplingMode) {
  25618. var sampling = parsedTexture.samplingMode;
  25619. if (texture._samplingMode !== sampling) {
  25620. texture.updateSamplingMode(sampling);
  25621. }
  25622. }
  25623. // Animations
  25624. if (parsedTexture.animations) {
  25625. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25626. var parsedAnimation = parsedTexture.animations[animationIndex];
  25627. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25628. }
  25629. }
  25630. return texture;
  25631. };
  25632. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25633. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25634. if (noMipmap === void 0) { noMipmap = false; }
  25635. if (invertY === void 0) { invertY = true; }
  25636. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25637. if (onLoad === void 0) { onLoad = null; }
  25638. if (onError === void 0) { onError = null; }
  25639. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25640. if (name.substr(0, 5) !== "data:") {
  25641. name = "data:" + name;
  25642. }
  25643. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25644. };
  25645. // Constants
  25646. Texture.NEAREST_SAMPLINGMODE = 1;
  25647. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25648. Texture.BILINEAR_SAMPLINGMODE = 2;
  25649. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25650. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25651. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25652. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25653. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25654. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25655. Texture.NEAREST_LINEAR = 7;
  25656. Texture.NEAREST_NEAREST = 8;
  25657. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25658. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25659. Texture.LINEAR_LINEAR = 11;
  25660. Texture.LINEAR_NEAREST = 12;
  25661. Texture.EXPLICIT_MODE = 0;
  25662. Texture.SPHERICAL_MODE = 1;
  25663. Texture.PLANAR_MODE = 2;
  25664. Texture.CUBIC_MODE = 3;
  25665. Texture.PROJECTION_MODE = 4;
  25666. Texture.SKYBOX_MODE = 5;
  25667. Texture.INVCUBIC_MODE = 6;
  25668. Texture.EQUIRECTANGULAR_MODE = 7;
  25669. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25670. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25671. Texture.CLAMP_ADDRESSMODE = 0;
  25672. Texture.WRAP_ADDRESSMODE = 1;
  25673. Texture.MIRROR_ADDRESSMODE = 2;
  25674. __decorate([
  25675. BABYLON.serialize()
  25676. ], Texture.prototype, "url", void 0);
  25677. __decorate([
  25678. BABYLON.serialize()
  25679. ], Texture.prototype, "uOffset", void 0);
  25680. __decorate([
  25681. BABYLON.serialize()
  25682. ], Texture.prototype, "vOffset", void 0);
  25683. __decorate([
  25684. BABYLON.serialize()
  25685. ], Texture.prototype, "uScale", void 0);
  25686. __decorate([
  25687. BABYLON.serialize()
  25688. ], Texture.prototype, "vScale", void 0);
  25689. __decorate([
  25690. BABYLON.serialize()
  25691. ], Texture.prototype, "uAng", void 0);
  25692. __decorate([
  25693. BABYLON.serialize()
  25694. ], Texture.prototype, "vAng", void 0);
  25695. __decorate([
  25696. BABYLON.serialize()
  25697. ], Texture.prototype, "wAng", void 0);
  25698. __decorate([
  25699. BABYLON.serialize()
  25700. ], Texture.prototype, "isBlocking", null);
  25701. return Texture;
  25702. }(BABYLON.BaseTexture));
  25703. BABYLON.Texture = Texture;
  25704. })(BABYLON || (BABYLON = {}));
  25705. //# sourceMappingURL=babylon.texture.js.map
  25706. var BABYLON;
  25707. (function (BABYLON) {
  25708. var _InstancesBatch = /** @class */ (function () {
  25709. function _InstancesBatch() {
  25710. this.mustReturn = false;
  25711. this.visibleInstances = new Array();
  25712. this.renderSelf = new Array();
  25713. }
  25714. return _InstancesBatch;
  25715. }());
  25716. BABYLON._InstancesBatch = _InstancesBatch;
  25717. var Mesh = /** @class */ (function (_super) {
  25718. __extends(Mesh, _super);
  25719. /**
  25720. * @constructor
  25721. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25722. * @param {Scene} scene The scene to add this mesh to.
  25723. * @param {Node} parent The parent of this mesh, if it has one
  25724. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25725. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25726. * When false, achieved by calling a clone(), also passing False.
  25727. * This will make creation of children, recursive.
  25728. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25729. */
  25730. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25731. if (scene === void 0) { scene = null; }
  25732. if (parent === void 0) { parent = null; }
  25733. if (source === void 0) { source = null; }
  25734. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25735. var _this = _super.call(this, name, scene) || this;
  25736. // Events
  25737. /**
  25738. * An event triggered before rendering the mesh
  25739. * @type {BABYLON.Observable}
  25740. */
  25741. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25742. /**
  25743. * An event triggered after rendering the mesh
  25744. * @type {BABYLON.Observable}
  25745. */
  25746. _this.onAfterRenderObservable = new BABYLON.Observable();
  25747. /**
  25748. * An event triggered before drawing the mesh
  25749. * @type {BABYLON.Observable}
  25750. */
  25751. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25752. // Members
  25753. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25754. _this.instances = new Array();
  25755. _this._LODLevels = new Array();
  25756. _this._visibleInstances = {};
  25757. _this._renderIdForInstances = new Array();
  25758. _this._batchCache = new _InstancesBatch();
  25759. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25760. // Use by builder only to know what orientation were the mesh build in.
  25761. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25762. _this.overrideMaterialSideOrientation = null;
  25763. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25764. // Will be used to save a source mesh reference, If any
  25765. _this._source = null;
  25766. scene = _this.getScene();
  25767. if (source) {
  25768. // Source mesh
  25769. _this._source = source;
  25770. // Geometry
  25771. if (source._geometry) {
  25772. source._geometry.applyToMesh(_this);
  25773. }
  25774. // Deep copy
  25775. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25776. // Metadata
  25777. if (source.metadata && source.metadata.clone) {
  25778. _this.metadata = source.metadata.clone();
  25779. }
  25780. else {
  25781. _this.metadata = source.metadata;
  25782. }
  25783. // Tags
  25784. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25785. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25786. }
  25787. // Parent
  25788. _this.parent = source.parent;
  25789. // Pivot
  25790. _this.setPivotMatrix(source.getPivotMatrix());
  25791. _this.id = name + "." + source.id;
  25792. // Material
  25793. _this.material = source.material;
  25794. var index;
  25795. if (!doNotCloneChildren) {
  25796. // Children
  25797. var directDescendants = source.getDescendants(true);
  25798. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25799. var child = directDescendants[index_1];
  25800. if (child.clone) {
  25801. child.clone(name + "." + child.name, _this);
  25802. }
  25803. }
  25804. }
  25805. // Physics clone
  25806. var physicsEngine = _this.getScene().getPhysicsEngine();
  25807. if (clonePhysicsImpostor && physicsEngine) {
  25808. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25809. if (impostor) {
  25810. _this.physicsImpostor = impostor.clone(_this);
  25811. }
  25812. }
  25813. // Particles
  25814. for (index = 0; index < scene.particleSystems.length; index++) {
  25815. var system = scene.particleSystems[index];
  25816. if (system.emitter === source) {
  25817. system.clone(system.name, _this);
  25818. }
  25819. }
  25820. _this.computeWorldMatrix(true);
  25821. }
  25822. // Parent
  25823. if (parent !== null) {
  25824. _this.parent = parent;
  25825. }
  25826. return _this;
  25827. }
  25828. Object.defineProperty(Mesh, "FRONTSIDE", {
  25829. /**
  25830. * Mesh side orientation : usually the external or front surface
  25831. */
  25832. get: function () {
  25833. return Mesh._FRONTSIDE;
  25834. },
  25835. enumerable: true,
  25836. configurable: true
  25837. });
  25838. Object.defineProperty(Mesh, "BACKSIDE", {
  25839. /**
  25840. * Mesh side orientation : usually the internal or back surface
  25841. */
  25842. get: function () {
  25843. return Mesh._BACKSIDE;
  25844. },
  25845. enumerable: true,
  25846. configurable: true
  25847. });
  25848. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25849. /**
  25850. * Mesh side orientation : both internal and external or front and back surfaces
  25851. */
  25852. get: function () {
  25853. return Mesh._DOUBLESIDE;
  25854. },
  25855. enumerable: true,
  25856. configurable: true
  25857. });
  25858. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25859. /**
  25860. * Mesh side orientation : by default, `FRONTSIDE`
  25861. */
  25862. get: function () {
  25863. return Mesh._DEFAULTSIDE;
  25864. },
  25865. enumerable: true,
  25866. configurable: true
  25867. });
  25868. Object.defineProperty(Mesh, "NO_CAP", {
  25869. /**
  25870. * Mesh cap setting : no cap
  25871. */
  25872. get: function () {
  25873. return Mesh._NO_CAP;
  25874. },
  25875. enumerable: true,
  25876. configurable: true
  25877. });
  25878. Object.defineProperty(Mesh, "CAP_START", {
  25879. /**
  25880. * Mesh cap setting : one cap at the beginning of the mesh
  25881. */
  25882. get: function () {
  25883. return Mesh._CAP_START;
  25884. },
  25885. enumerable: true,
  25886. configurable: true
  25887. });
  25888. Object.defineProperty(Mesh, "CAP_END", {
  25889. /**
  25890. * Mesh cap setting : one cap at the end of the mesh
  25891. */
  25892. get: function () {
  25893. return Mesh._CAP_END;
  25894. },
  25895. enumerable: true,
  25896. configurable: true
  25897. });
  25898. Object.defineProperty(Mesh, "CAP_ALL", {
  25899. /**
  25900. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25901. */
  25902. get: function () {
  25903. return Mesh._CAP_ALL;
  25904. },
  25905. enumerable: true,
  25906. configurable: true
  25907. });
  25908. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25909. set: function (callback) {
  25910. if (this._onBeforeDrawObserver) {
  25911. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25912. }
  25913. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25919. get: function () {
  25920. return this._morphTargetManager;
  25921. },
  25922. set: function (value) {
  25923. if (this._morphTargetManager === value) {
  25924. return;
  25925. }
  25926. this._morphTargetManager = value;
  25927. this._syncGeometryWithMorphTargetManager();
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. Object.defineProperty(Mesh.prototype, "source", {
  25933. get: function () {
  25934. return this._source;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25940. get: function () {
  25941. return this._unIndexed;
  25942. },
  25943. set: function (value) {
  25944. if (this._unIndexed !== value) {
  25945. this._unIndexed = value;
  25946. this._markSubMeshesAsAttributesDirty();
  25947. }
  25948. },
  25949. enumerable: true,
  25950. configurable: true
  25951. });
  25952. // Methods
  25953. /**
  25954. * Returns the string "Mesh".
  25955. */
  25956. Mesh.prototype.getClassName = function () {
  25957. return "Mesh";
  25958. };
  25959. /**
  25960. * Returns a string.
  25961. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25962. */
  25963. Mesh.prototype.toString = function (fullDetails) {
  25964. var ret = _super.prototype.toString.call(this, fullDetails);
  25965. ret += ", n vertices: " + this.getTotalVertices();
  25966. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25967. if (this.animations) {
  25968. for (var i = 0; i < this.animations.length; i++) {
  25969. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25970. }
  25971. }
  25972. if (fullDetails) {
  25973. if (this._geometry) {
  25974. var ib = this.getIndices();
  25975. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25976. if (vb && ib) {
  25977. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25978. }
  25979. }
  25980. else {
  25981. ret += ", flat shading: UNKNOWN";
  25982. }
  25983. }
  25984. return ret;
  25985. };
  25986. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25987. /**
  25988. * True if the mesh has some Levels Of Details (LOD).
  25989. * Returns a boolean.
  25990. */
  25991. get: function () {
  25992. return this._LODLevels.length > 0;
  25993. },
  25994. enumerable: true,
  25995. configurable: true
  25996. });
  25997. /**
  25998. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25999. * @returns an array of {BABYLON.MeshLODLevel}
  26000. */
  26001. Mesh.prototype.getLODLevels = function () {
  26002. return this._LODLevels;
  26003. };
  26004. Mesh.prototype._sortLODLevels = function () {
  26005. this._LODLevels.sort(function (a, b) {
  26006. if (a.distance < b.distance) {
  26007. return 1;
  26008. }
  26009. if (a.distance > b.distance) {
  26010. return -1;
  26011. }
  26012. return 0;
  26013. });
  26014. };
  26015. /**
  26016. * Add a mesh as LOD level triggered at the given distance.
  26017. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26018. * @param {number} distance The distance from the center of the object to show this level
  26019. * @param {Mesh} mesh The mesh to be added as LOD level
  26020. * @return {Mesh} This mesh (for chaining)
  26021. */
  26022. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26023. if (mesh && mesh._masterMesh) {
  26024. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26025. return this;
  26026. }
  26027. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26028. this._LODLevels.push(level);
  26029. if (mesh) {
  26030. mesh._masterMesh = this;
  26031. }
  26032. this._sortLODLevels();
  26033. return this;
  26034. };
  26035. /**
  26036. * Returns the LOD level mesh at the passed distance or null if not found.
  26037. * It is related to the method `addLODLevel(distance, mesh)`.
  26038. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26039. * Returns an object Mesh or `null`.
  26040. */
  26041. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26042. for (var index = 0; index < this._LODLevels.length; index++) {
  26043. var level = this._LODLevels[index];
  26044. if (level.distance === distance) {
  26045. return level.mesh;
  26046. }
  26047. }
  26048. return null;
  26049. };
  26050. /**
  26051. * Remove a mesh from the LOD array
  26052. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26053. * @param {Mesh} mesh The mesh to be removed.
  26054. * @return {Mesh} This mesh (for chaining)
  26055. */
  26056. Mesh.prototype.removeLODLevel = function (mesh) {
  26057. for (var index = 0; index < this._LODLevels.length; index++) {
  26058. if (this._LODLevels[index].mesh === mesh) {
  26059. this._LODLevels.splice(index, 1);
  26060. if (mesh) {
  26061. mesh._masterMesh = null;
  26062. }
  26063. }
  26064. }
  26065. this._sortLODLevels();
  26066. return this;
  26067. };
  26068. /**
  26069. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26070. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26071. */
  26072. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26073. if (!this._LODLevels || this._LODLevels.length === 0) {
  26074. return this;
  26075. }
  26076. var bSphere;
  26077. if (boundingSphere) {
  26078. bSphere = boundingSphere;
  26079. }
  26080. else {
  26081. var boundingInfo = this.getBoundingInfo();
  26082. bSphere = boundingInfo.boundingSphere;
  26083. }
  26084. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26085. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26086. if (this.onLODLevelSelection) {
  26087. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26088. }
  26089. return this;
  26090. }
  26091. for (var index = 0; index < this._LODLevels.length; index++) {
  26092. var level = this._LODLevels[index];
  26093. if (level.distance < distanceToCamera) {
  26094. if (level.mesh) {
  26095. level.mesh._preActivate();
  26096. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26097. }
  26098. if (this.onLODLevelSelection) {
  26099. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26100. }
  26101. return level.mesh;
  26102. }
  26103. }
  26104. if (this.onLODLevelSelection) {
  26105. this.onLODLevelSelection(distanceToCamera, this, this);
  26106. }
  26107. return this;
  26108. };
  26109. Object.defineProperty(Mesh.prototype, "geometry", {
  26110. /**
  26111. * Returns the mesh internal Geometry object.
  26112. */
  26113. get: function () {
  26114. return this._geometry;
  26115. },
  26116. enumerable: true,
  26117. configurable: true
  26118. });
  26119. /**
  26120. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26121. */
  26122. Mesh.prototype.getTotalVertices = function () {
  26123. if (this._geometry === null || this._geometry === undefined) {
  26124. return 0;
  26125. }
  26126. return this._geometry.getTotalVertices();
  26127. };
  26128. /**
  26129. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26130. * 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.
  26131. * You can force the copy with forceCopy === true
  26132. * Returns null if the mesh has no geometry or no vertex buffer.
  26133. * Possible `kind` values :
  26134. * - BABYLON.VertexBuffer.PositionKind
  26135. * - BABYLON.VertexBuffer.UVKind
  26136. * - BABYLON.VertexBuffer.UV2Kind
  26137. * - BABYLON.VertexBuffer.UV3Kind
  26138. * - BABYLON.VertexBuffer.UV4Kind
  26139. * - BABYLON.VertexBuffer.UV5Kind
  26140. * - BABYLON.VertexBuffer.UV6Kind
  26141. * - BABYLON.VertexBuffer.ColorKind
  26142. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26143. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26144. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26145. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26146. */
  26147. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26148. if (!this._geometry) {
  26149. return null;
  26150. }
  26151. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26152. };
  26153. /**
  26154. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26155. * Returns `null` if the mesh has no geometry.
  26156. * Possible `kind` values :
  26157. * - BABYLON.VertexBuffer.PositionKind
  26158. * - BABYLON.VertexBuffer.UVKind
  26159. * - BABYLON.VertexBuffer.UV2Kind
  26160. * - BABYLON.VertexBuffer.UV3Kind
  26161. * - BABYLON.VertexBuffer.UV4Kind
  26162. * - BABYLON.VertexBuffer.UV5Kind
  26163. * - BABYLON.VertexBuffer.UV6Kind
  26164. * - BABYLON.VertexBuffer.ColorKind
  26165. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26166. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26167. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26168. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26169. */
  26170. Mesh.prototype.getVertexBuffer = function (kind) {
  26171. if (!this._geometry) {
  26172. return null;
  26173. }
  26174. return this._geometry.getVertexBuffer(kind);
  26175. };
  26176. /**
  26177. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26178. * Possible `kind` values :
  26179. * - BABYLON.VertexBuffer.PositionKind
  26180. * - BABYLON.VertexBuffer.UVKind
  26181. * - BABYLON.VertexBuffer.UV2Kind
  26182. * - BABYLON.VertexBuffer.UV3Kind
  26183. * - BABYLON.VertexBuffer.UV4Kind
  26184. * - BABYLON.VertexBuffer.UV5Kind
  26185. * - BABYLON.VertexBuffer.UV6Kind
  26186. * - BABYLON.VertexBuffer.ColorKind
  26187. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26188. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26189. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26190. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26191. */
  26192. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26193. if (!this._geometry) {
  26194. if (this._delayInfo) {
  26195. return this._delayInfo.indexOf(kind) !== -1;
  26196. }
  26197. return false;
  26198. }
  26199. return this._geometry.isVerticesDataPresent(kind);
  26200. };
  26201. /**
  26202. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26203. * Possible `kind` values :
  26204. * - BABYLON.VertexBuffer.PositionKind
  26205. * - BABYLON.VertexBuffer.UVKind
  26206. * - BABYLON.VertexBuffer.UV2Kind
  26207. * - BABYLON.VertexBuffer.UV3Kind
  26208. * - BABYLON.VertexBuffer.UV4Kind
  26209. * - BABYLON.VertexBuffer.UV5Kind
  26210. * - BABYLON.VertexBuffer.UV6Kind
  26211. * - BABYLON.VertexBuffer.ColorKind
  26212. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26213. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26214. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26215. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26216. */
  26217. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26218. if (!this._geometry) {
  26219. if (this._delayInfo) {
  26220. return this._delayInfo.indexOf(kind) !== -1;
  26221. }
  26222. return false;
  26223. }
  26224. return this._geometry.isVertexBufferUpdatable(kind);
  26225. };
  26226. /**
  26227. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26228. * Possible `kind` values :
  26229. * - BABYLON.VertexBuffer.PositionKind
  26230. * - BABYLON.VertexBuffer.UVKind
  26231. * - BABYLON.VertexBuffer.UV2Kind
  26232. * - BABYLON.VertexBuffer.UV3Kind
  26233. * - BABYLON.VertexBuffer.UV4Kind
  26234. * - BABYLON.VertexBuffer.UV5Kind
  26235. * - BABYLON.VertexBuffer.UV6Kind
  26236. * - BABYLON.VertexBuffer.ColorKind
  26237. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26238. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26239. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26240. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26241. */
  26242. Mesh.prototype.getVerticesDataKinds = function () {
  26243. if (!this._geometry) {
  26244. var result = new Array();
  26245. if (this._delayInfo) {
  26246. this._delayInfo.forEach(function (kind, index, array) {
  26247. result.push(kind);
  26248. });
  26249. }
  26250. return result;
  26251. }
  26252. return this._geometry.getVerticesDataKinds();
  26253. };
  26254. /**
  26255. * Returns a positive integer : the total number of indices in this mesh geometry.
  26256. * Returns zero if the mesh has no geometry.
  26257. */
  26258. Mesh.prototype.getTotalIndices = function () {
  26259. if (!this._geometry) {
  26260. return 0;
  26261. }
  26262. return this._geometry.getTotalIndices();
  26263. };
  26264. /**
  26265. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26266. * 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.
  26267. * Returns an empty array if the mesh has no geometry.
  26268. */
  26269. Mesh.prototype.getIndices = function (copyWhenShared) {
  26270. if (!this._geometry) {
  26271. return [];
  26272. }
  26273. return this._geometry.getIndices(copyWhenShared);
  26274. };
  26275. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26276. get: function () {
  26277. return this._masterMesh !== null && this._masterMesh !== undefined;
  26278. },
  26279. enumerable: true,
  26280. configurable: true
  26281. });
  26282. /**
  26283. * Determine if the current mesh is ready to be rendered
  26284. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26285. * @returns true if all associated assets are ready (material, textures, shaders)
  26286. */
  26287. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26288. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26289. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26290. return false;
  26291. }
  26292. if (!_super.prototype.isReady.call(this)) {
  26293. return false;
  26294. }
  26295. if (!this.subMeshes || this.subMeshes.length === 0) {
  26296. return true;
  26297. }
  26298. var engine = this.getEngine();
  26299. var scene = this.getScene();
  26300. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26301. this.computeWorldMatrix();
  26302. var mat = this.material || scene.defaultMaterial;
  26303. if (mat) {
  26304. if (mat.storeEffectOnSubMeshes) {
  26305. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26306. var subMesh = _a[_i];
  26307. var effectiveMaterial = subMesh.getMaterial();
  26308. if (effectiveMaterial) {
  26309. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26310. return false;
  26311. }
  26312. }
  26313. }
  26314. }
  26315. else {
  26316. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26317. return false;
  26318. }
  26319. }
  26320. }
  26321. // Shadows
  26322. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26323. var light = _c[_b];
  26324. var generator = light.getShadowGenerator();
  26325. if (generator) {
  26326. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26327. var subMesh = _e[_d];
  26328. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26329. return false;
  26330. }
  26331. }
  26332. }
  26333. }
  26334. // LOD
  26335. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26336. var lod = _g[_f];
  26337. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26338. return false;
  26339. }
  26340. }
  26341. return true;
  26342. };
  26343. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26344. /**
  26345. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26346. * This property is pertinent only for updatable parametric shapes.
  26347. */
  26348. get: function () {
  26349. return this._areNormalsFrozen;
  26350. },
  26351. enumerable: true,
  26352. configurable: true
  26353. });
  26354. /**
  26355. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26356. * It has no effect at all on other shapes.
  26357. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26358. * Returns the Mesh.
  26359. */
  26360. Mesh.prototype.freezeNormals = function () {
  26361. this._areNormalsFrozen = true;
  26362. return this;
  26363. };
  26364. /**
  26365. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26366. * It has no effect at all on other shapes.
  26367. * It reactivates the mesh normals computation if it was previously frozen.
  26368. * Returns the Mesh.
  26369. */
  26370. Mesh.prototype.unfreezeNormals = function () {
  26371. this._areNormalsFrozen = false;
  26372. return this;
  26373. };
  26374. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26375. /**
  26376. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26377. */
  26378. set: function (count) {
  26379. this._overridenInstanceCount = count;
  26380. },
  26381. enumerable: true,
  26382. configurable: true
  26383. });
  26384. // Methods
  26385. Mesh.prototype._preActivate = function () {
  26386. var sceneRenderId = this.getScene().getRenderId();
  26387. if (this._preActivateId === sceneRenderId) {
  26388. return this;
  26389. }
  26390. this._preActivateId = sceneRenderId;
  26391. this._visibleInstances = null;
  26392. return this;
  26393. };
  26394. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26395. if (this._visibleInstances) {
  26396. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26397. }
  26398. return this;
  26399. };
  26400. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26401. if (!this._visibleInstances) {
  26402. this._visibleInstances = {};
  26403. this._visibleInstances.defaultRenderId = renderId;
  26404. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26405. }
  26406. if (!this._visibleInstances[renderId]) {
  26407. this._visibleInstances[renderId] = new Array();
  26408. }
  26409. this._visibleInstances[renderId].push(instance);
  26410. return this;
  26411. };
  26412. /**
  26413. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26414. * This means the mesh underlying bounding box and sphere are recomputed.
  26415. * Returns the Mesh.
  26416. */
  26417. Mesh.prototype.refreshBoundingInfo = function () {
  26418. return this._refreshBoundingInfo(false);
  26419. };
  26420. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26421. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26422. return this;
  26423. }
  26424. var data = this._getPositionData(applySkeleton);
  26425. if (data) {
  26426. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26427. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26428. }
  26429. if (this.subMeshes) {
  26430. for (var index = 0; index < this.subMeshes.length; index++) {
  26431. this.subMeshes[index].refreshBoundingInfo();
  26432. }
  26433. }
  26434. this._updateBoundingInfo();
  26435. return this;
  26436. };
  26437. Mesh.prototype._getPositionData = function (applySkeleton) {
  26438. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26439. if (data && applySkeleton && this.skeleton) {
  26440. data = BABYLON.Tools.Slice(data);
  26441. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26442. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26443. if (matricesWeightsData && matricesIndicesData) {
  26444. var needExtras = this.numBoneInfluencers > 4;
  26445. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26446. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26447. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26448. var tempVector = BABYLON.Tmp.Vector3[0];
  26449. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26450. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26451. var matWeightIdx = 0;
  26452. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26453. finalMatrix.reset();
  26454. var inf;
  26455. var weight;
  26456. for (inf = 0; inf < 4; inf++) {
  26457. weight = matricesWeightsData[matWeightIdx + inf];
  26458. if (weight <= 0)
  26459. break;
  26460. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26461. finalMatrix.addToSelf(tempMatrix);
  26462. }
  26463. if (needExtras) {
  26464. for (inf = 0; inf < 4; inf++) {
  26465. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26466. if (weight <= 0)
  26467. break;
  26468. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26469. finalMatrix.addToSelf(tempMatrix);
  26470. }
  26471. }
  26472. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26473. tempVector.toArray(data, index);
  26474. }
  26475. }
  26476. }
  26477. return data;
  26478. };
  26479. Mesh.prototype._createGlobalSubMesh = function (force) {
  26480. var totalVertices = this.getTotalVertices();
  26481. if (!totalVertices || !this.getIndices()) {
  26482. return null;
  26483. }
  26484. // Check if we need to recreate the submeshes
  26485. if (this.subMeshes && this.subMeshes.length > 0) {
  26486. var ib = this.getIndices();
  26487. if (!ib) {
  26488. return null;
  26489. }
  26490. var totalIndices = ib.length;
  26491. var needToRecreate = false;
  26492. if (force) {
  26493. needToRecreate = true;
  26494. }
  26495. else {
  26496. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26497. var submesh = _a[_i];
  26498. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26499. needToRecreate = true;
  26500. break;
  26501. }
  26502. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26503. needToRecreate = true;
  26504. break;
  26505. }
  26506. }
  26507. }
  26508. if (!needToRecreate) {
  26509. return this.subMeshes[0];
  26510. }
  26511. }
  26512. this.releaseSubMeshes();
  26513. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26514. };
  26515. Mesh.prototype.subdivide = function (count) {
  26516. if (count < 1) {
  26517. return;
  26518. }
  26519. var totalIndices = this.getTotalIndices();
  26520. var subdivisionSize = (totalIndices / count) | 0;
  26521. var offset = 0;
  26522. // Ensure that subdivisionSize is a multiple of 3
  26523. while (subdivisionSize % 3 !== 0) {
  26524. subdivisionSize++;
  26525. }
  26526. this.releaseSubMeshes();
  26527. for (var index = 0; index < count; index++) {
  26528. if (offset >= totalIndices) {
  26529. break;
  26530. }
  26531. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26532. offset += subdivisionSize;
  26533. }
  26534. this.synchronizeInstances();
  26535. };
  26536. /**
  26537. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26538. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26539. * The `data` are either a numeric array either a Float32Array.
  26540. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26541. * 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).
  26542. * Note that a new underlying VertexBuffer object is created each call.
  26543. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26544. *
  26545. * Possible `kind` values :
  26546. * - BABYLON.VertexBuffer.PositionKind
  26547. * - BABYLON.VertexBuffer.UVKind
  26548. * - BABYLON.VertexBuffer.UV2Kind
  26549. * - BABYLON.VertexBuffer.UV3Kind
  26550. * - BABYLON.VertexBuffer.UV4Kind
  26551. * - BABYLON.VertexBuffer.UV5Kind
  26552. * - BABYLON.VertexBuffer.UV6Kind
  26553. * - BABYLON.VertexBuffer.ColorKind
  26554. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26555. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26556. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26557. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26558. *
  26559. * Returns the Mesh.
  26560. */
  26561. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26562. if (updatable === void 0) { updatable = false; }
  26563. if (!this._geometry) {
  26564. var vertexData = new BABYLON.VertexData();
  26565. vertexData.set(data, kind);
  26566. var scene = this.getScene();
  26567. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26568. }
  26569. else {
  26570. this._geometry.setVerticesData(kind, data, updatable, stride);
  26571. }
  26572. return this;
  26573. };
  26574. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26575. if (updatable === void 0) { updatable = true; }
  26576. var vb = this.getVertexBuffer(kind);
  26577. if (!vb || vb.isUpdatable() === updatable) {
  26578. return;
  26579. }
  26580. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26581. };
  26582. /**
  26583. * Sets the mesh VertexBuffer.
  26584. * Returns the Mesh.
  26585. */
  26586. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26587. if (!this._geometry) {
  26588. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26589. }
  26590. this._geometry.setVerticesBuffer(buffer);
  26591. return this;
  26592. };
  26593. /**
  26594. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26595. * If the mesh has no geometry, it is simply returned as it is.
  26596. * The `data` are either a numeric array either a Float32Array.
  26597. * No new underlying VertexBuffer object is created.
  26598. * 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.
  26599. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26600. *
  26601. * Possible `kind` values :
  26602. * - BABYLON.VertexBuffer.PositionKind
  26603. * - BABYLON.VertexBuffer.UVKind
  26604. * - BABYLON.VertexBuffer.UV2Kind
  26605. * - BABYLON.VertexBuffer.UV3Kind
  26606. * - BABYLON.VertexBuffer.UV4Kind
  26607. * - BABYLON.VertexBuffer.UV5Kind
  26608. * - BABYLON.VertexBuffer.UV6Kind
  26609. * - BABYLON.VertexBuffer.ColorKind
  26610. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26611. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26612. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26613. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26614. *
  26615. * Returns the Mesh.
  26616. */
  26617. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26618. if (!this._geometry) {
  26619. return this;
  26620. }
  26621. if (!makeItUnique) {
  26622. this._geometry.updateVerticesData(kind, data, updateExtends);
  26623. }
  26624. else {
  26625. this.makeGeometryUnique();
  26626. this.updateVerticesData(kind, data, updateExtends, false);
  26627. }
  26628. return this;
  26629. };
  26630. /**
  26631. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26632. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26633. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26634. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26635. * Returns the Mesh.
  26636. */
  26637. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26638. if (computeNormals === void 0) { computeNormals = true; }
  26639. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26640. if (!positions) {
  26641. return this;
  26642. }
  26643. positionFunction(positions);
  26644. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26645. if (computeNormals) {
  26646. var indices = this.getIndices();
  26647. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26648. if (!normals) {
  26649. return this;
  26650. }
  26651. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26652. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26653. }
  26654. return this;
  26655. };
  26656. /**
  26657. * Creates a un-shared specific occurence of the geometry for the mesh.
  26658. * Returns the Mesh.
  26659. */
  26660. Mesh.prototype.makeGeometryUnique = function () {
  26661. if (!this._geometry) {
  26662. return this;
  26663. }
  26664. var oldGeometry = this._geometry;
  26665. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26666. oldGeometry.releaseForMesh(this, true);
  26667. geometry.applyToMesh(this);
  26668. return this;
  26669. };
  26670. /**
  26671. * Sets the mesh indices.
  26672. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26673. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26674. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26675. * This method creates a new index buffer each call.
  26676. * Returns the Mesh.
  26677. */
  26678. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26679. if (totalVertices === void 0) { totalVertices = null; }
  26680. if (updatable === void 0) { updatable = false; }
  26681. if (!this._geometry) {
  26682. var vertexData = new BABYLON.VertexData();
  26683. vertexData.indices = indices;
  26684. var scene = this.getScene();
  26685. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26686. }
  26687. else {
  26688. this._geometry.setIndices(indices, totalVertices, updatable);
  26689. }
  26690. return this;
  26691. };
  26692. /**
  26693. * Update the current index buffer
  26694. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26695. * Returns the Mesh.
  26696. */
  26697. Mesh.prototype.updateIndices = function (indices, offset) {
  26698. if (!this._geometry) {
  26699. return this;
  26700. }
  26701. this._geometry.updateIndices(indices, offset);
  26702. return this;
  26703. };
  26704. /**
  26705. * Invert the geometry to move from a right handed system to a left handed one.
  26706. * Returns the Mesh.
  26707. */
  26708. Mesh.prototype.toLeftHanded = function () {
  26709. if (!this._geometry) {
  26710. return this;
  26711. }
  26712. this._geometry.toLeftHanded();
  26713. return this;
  26714. };
  26715. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26716. if (!this._geometry) {
  26717. return this;
  26718. }
  26719. var engine = this.getScene().getEngine();
  26720. // Wireframe
  26721. var indexToBind;
  26722. if (this._unIndexed) {
  26723. indexToBind = null;
  26724. }
  26725. else {
  26726. switch (fillMode) {
  26727. case BABYLON.Material.PointFillMode:
  26728. indexToBind = null;
  26729. break;
  26730. case BABYLON.Material.WireFrameFillMode:
  26731. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26732. break;
  26733. default:
  26734. case BABYLON.Material.TriangleFillMode:
  26735. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26736. break;
  26737. }
  26738. }
  26739. // VBOs
  26740. this._geometry._bind(effect, indexToBind);
  26741. return this;
  26742. };
  26743. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26744. if (alternate === void 0) { alternate = false; }
  26745. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26746. return this;
  26747. }
  26748. this.onBeforeDrawObservable.notifyObservers(this);
  26749. var scene = this.getScene();
  26750. var engine = scene.getEngine();
  26751. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26752. // or triangles as points
  26753. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26754. }
  26755. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26756. // Triangles as wireframe
  26757. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26758. }
  26759. else {
  26760. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26761. }
  26762. if (scene._isAlternateRenderingEnabled && !alternate) {
  26763. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26764. if (!effect || !scene.activeCamera) {
  26765. return this;
  26766. }
  26767. scene._switchToAlternateCameraConfiguration(true);
  26768. this._effectiveMaterial.bindView(effect);
  26769. this._effectiveMaterial.bindViewProjection(effect);
  26770. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26771. this._draw(subMesh, fillMode, instancesCount, true);
  26772. engine.setViewport(scene.activeCamera.viewport);
  26773. scene._switchToAlternateCameraConfiguration(false);
  26774. this._effectiveMaterial.bindView(effect);
  26775. this._effectiveMaterial.bindViewProjection(effect);
  26776. }
  26777. return this;
  26778. };
  26779. /**
  26780. * Registers for this mesh a javascript function called just before the rendering process.
  26781. * This function is passed the current mesh.
  26782. * Return the Mesh.
  26783. */
  26784. Mesh.prototype.registerBeforeRender = function (func) {
  26785. this.onBeforeRenderObservable.add(func);
  26786. return this;
  26787. };
  26788. /**
  26789. * Disposes a previously registered javascript function called before the rendering.
  26790. * This function is passed the current mesh.
  26791. * Returns the Mesh.
  26792. */
  26793. Mesh.prototype.unregisterBeforeRender = function (func) {
  26794. this.onBeforeRenderObservable.removeCallback(func);
  26795. return this;
  26796. };
  26797. /**
  26798. * Registers for this mesh a javascript function called just after the rendering is complete.
  26799. * This function is passed the current mesh.
  26800. * Returns the Mesh.
  26801. */
  26802. Mesh.prototype.registerAfterRender = function (func) {
  26803. this.onAfterRenderObservable.add(func);
  26804. return this;
  26805. };
  26806. /**
  26807. * Disposes a previously registered javascript function called after the rendering.
  26808. * This function is passed the current mesh.
  26809. * Return the Mesh.
  26810. */
  26811. Mesh.prototype.unregisterAfterRender = function (func) {
  26812. this.onAfterRenderObservable.removeCallback(func);
  26813. return this;
  26814. };
  26815. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26816. var scene = this.getScene();
  26817. this._batchCache.mustReturn = false;
  26818. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26819. this._batchCache.visibleInstances[subMeshId] = null;
  26820. if (this._visibleInstances) {
  26821. var currentRenderId = scene.getRenderId();
  26822. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26823. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26824. var selfRenderId = this._renderId;
  26825. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26826. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26827. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26828. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26829. }
  26830. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26831. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26832. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26833. this._batchCache.mustReturn = true;
  26834. return this._batchCache;
  26835. }
  26836. if (currentRenderId !== selfRenderId) {
  26837. this._batchCache.renderSelf[subMeshId] = false;
  26838. }
  26839. }
  26840. this._renderIdForInstances[subMeshId] = currentRenderId;
  26841. }
  26842. return this._batchCache;
  26843. };
  26844. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26845. var visibleInstances = batch.visibleInstances[subMesh._id];
  26846. if (!visibleInstances) {
  26847. return this;
  26848. }
  26849. var matricesCount = visibleInstances.length + 1;
  26850. var bufferSize = matricesCount * 16 * 4;
  26851. var currentInstancesBufferSize = this._instancesBufferSize;
  26852. var instancesBuffer = this._instancesBuffer;
  26853. while (this._instancesBufferSize < bufferSize) {
  26854. this._instancesBufferSize *= 2;
  26855. }
  26856. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26857. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26858. }
  26859. var offset = 0;
  26860. var instancesCount = 0;
  26861. var world = this.getWorldMatrix();
  26862. if (batch.renderSelf[subMesh._id]) {
  26863. world.copyToArray(this._instancesData, offset);
  26864. offset += 16;
  26865. instancesCount++;
  26866. }
  26867. if (visibleInstances) {
  26868. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26869. var instance = visibleInstances[instanceIndex];
  26870. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26871. offset += 16;
  26872. instancesCount++;
  26873. }
  26874. }
  26875. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26876. if (instancesBuffer) {
  26877. instancesBuffer.dispose();
  26878. }
  26879. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26880. this._instancesBuffer = instancesBuffer;
  26881. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26882. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26883. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26884. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26885. }
  26886. else {
  26887. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26888. }
  26889. this._bind(subMesh, effect, fillMode);
  26890. this._draw(subMesh, fillMode, instancesCount);
  26891. engine.unbindInstanceAttributes();
  26892. return this;
  26893. };
  26894. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26895. var scene = this.getScene();
  26896. var engine = scene.getEngine();
  26897. if (hardwareInstancedRendering) {
  26898. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26899. }
  26900. else {
  26901. if (batch.renderSelf[subMesh._id]) {
  26902. // Draw
  26903. if (onBeforeDraw) {
  26904. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26905. }
  26906. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26907. }
  26908. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26909. if (visibleInstancesForSubMesh) {
  26910. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26911. var instance = visibleInstancesForSubMesh[instanceIndex];
  26912. // World
  26913. var world = instance.getWorldMatrix();
  26914. if (onBeforeDraw) {
  26915. onBeforeDraw(true, world, effectiveMaterial);
  26916. }
  26917. // Draw
  26918. this._draw(subMesh, fillMode);
  26919. }
  26920. }
  26921. }
  26922. return this;
  26923. };
  26924. /**
  26925. * Triggers the draw call for the mesh.
  26926. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26927. * Returns the Mesh.
  26928. */
  26929. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26930. this.checkOcclusionQuery();
  26931. if (this._isOccluded) {
  26932. return this;
  26933. }
  26934. var scene = this.getScene();
  26935. // Managing instances
  26936. var batch = this._getInstancesRenderList(subMesh._id);
  26937. if (batch.mustReturn) {
  26938. return this;
  26939. }
  26940. // Checking geometry state
  26941. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26942. return this;
  26943. }
  26944. this.onBeforeRenderObservable.notifyObservers(this);
  26945. var engine = scene.getEngine();
  26946. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26947. // Material
  26948. var material = subMesh.getMaterial();
  26949. if (!material) {
  26950. return this;
  26951. }
  26952. this._effectiveMaterial = material;
  26953. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26954. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26955. return this;
  26956. }
  26957. }
  26958. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26959. return this;
  26960. }
  26961. // Alpha mode
  26962. if (enableAlphaMode) {
  26963. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26964. }
  26965. // Outline - step 1
  26966. var savedDepthWrite = engine.getDepthWrite();
  26967. if (this.renderOutline) {
  26968. engine.setDepthWrite(false);
  26969. scene.getOutlineRenderer().render(subMesh, batch);
  26970. engine.setDepthWrite(savedDepthWrite);
  26971. }
  26972. var effect;
  26973. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26974. effect = subMesh.effect;
  26975. }
  26976. else {
  26977. effect = this._effectiveMaterial.getEffect();
  26978. }
  26979. if (!effect) {
  26980. return this;
  26981. }
  26982. var sideOrientation = this.overrideMaterialSideOrientation;
  26983. if (sideOrientation == null) {
  26984. sideOrientation = this._effectiveMaterial.sideOrientation;
  26985. if (this._getWorldMatrixDeterminant() < 0) {
  26986. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26987. }
  26988. }
  26989. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26990. if (this._effectiveMaterial.forceDepthWrite) {
  26991. engine.setDepthWrite(true);
  26992. }
  26993. // Bind
  26994. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26995. if (!hardwareInstancedRendering) {
  26996. this._bind(subMesh, effect, fillMode);
  26997. }
  26998. var world = this.getWorldMatrix();
  26999. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27000. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27001. }
  27002. else {
  27003. this._effectiveMaterial.bind(world, this);
  27004. }
  27005. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27006. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27007. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27008. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27009. }
  27010. // Draw
  27011. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27012. // Unbind
  27013. this._effectiveMaterial.unbind();
  27014. // Outline - step 2
  27015. if (this.renderOutline && savedDepthWrite) {
  27016. engine.setDepthWrite(true);
  27017. engine.setColorWrite(false);
  27018. scene.getOutlineRenderer().render(subMesh, batch);
  27019. engine.setColorWrite(true);
  27020. }
  27021. // Overlay
  27022. if (this.renderOverlay) {
  27023. var currentMode = engine.getAlphaMode();
  27024. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27025. scene.getOutlineRenderer().render(subMesh, batch, true);
  27026. engine.setAlphaMode(currentMode);
  27027. }
  27028. this.onAfterRenderObservable.notifyObservers(this);
  27029. return this;
  27030. };
  27031. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27032. if (isInstance && effectiveMaterial) {
  27033. effectiveMaterial.bindOnlyWorldMatrix(world);
  27034. }
  27035. };
  27036. /**
  27037. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27038. */
  27039. Mesh.prototype.getEmittedParticleSystems = function () {
  27040. var results = new Array();
  27041. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27042. var particleSystem = this.getScene().particleSystems[index];
  27043. if (particleSystem.emitter === this) {
  27044. results.push(particleSystem);
  27045. }
  27046. }
  27047. return results;
  27048. };
  27049. /**
  27050. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27051. */
  27052. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27053. var results = new Array();
  27054. var descendants = this.getDescendants();
  27055. descendants.push(this);
  27056. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27057. var particleSystem = this.getScene().particleSystems[index];
  27058. var emitter = particleSystem.emitter;
  27059. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27060. results.push(particleSystem);
  27061. }
  27062. }
  27063. return results;
  27064. };
  27065. Mesh.prototype._checkDelayState = function () {
  27066. var scene = this.getScene();
  27067. if (this._geometry) {
  27068. this._geometry.load(scene);
  27069. }
  27070. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27071. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27072. this._queueLoad(scene);
  27073. }
  27074. return this;
  27075. };
  27076. Mesh.prototype._queueLoad = function (scene) {
  27077. var _this = this;
  27078. scene._addPendingData(this);
  27079. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27080. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27081. if (data instanceof ArrayBuffer) {
  27082. _this._delayLoadingFunction(data, _this);
  27083. }
  27084. else {
  27085. _this._delayLoadingFunction(JSON.parse(data), _this);
  27086. }
  27087. _this.instances.forEach(function (instance) {
  27088. instance._syncSubMeshes();
  27089. });
  27090. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27091. scene._removePendingData(_this);
  27092. }, function () { }, scene.database, getBinaryData);
  27093. return this;
  27094. };
  27095. /**
  27096. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27097. */
  27098. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27099. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27100. return false;
  27101. }
  27102. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27103. return false;
  27104. }
  27105. this._checkDelayState();
  27106. return true;
  27107. };
  27108. /**
  27109. * Sets the mesh material by the material or multiMaterial `id` property.
  27110. * The material `id` is a string identifying the material or the multiMaterial.
  27111. * This method returns the Mesh.
  27112. */
  27113. Mesh.prototype.setMaterialByID = function (id) {
  27114. var materials = this.getScene().materials;
  27115. var index;
  27116. for (index = materials.length - 1; index > -1; index--) {
  27117. if (materials[index].id === id) {
  27118. this.material = materials[index];
  27119. return this;
  27120. }
  27121. }
  27122. // Multi
  27123. var multiMaterials = this.getScene().multiMaterials;
  27124. for (index = multiMaterials.length - 1; index > -1; index--) {
  27125. if (multiMaterials[index].id === id) {
  27126. this.material = multiMaterials[index];
  27127. return this;
  27128. }
  27129. }
  27130. return this;
  27131. };
  27132. /**
  27133. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27134. */
  27135. Mesh.prototype.getAnimatables = function () {
  27136. var results = new Array();
  27137. if (this.material) {
  27138. results.push(this.material);
  27139. }
  27140. if (this.skeleton) {
  27141. results.push(this.skeleton);
  27142. }
  27143. return results;
  27144. };
  27145. /**
  27146. * Modifies the mesh geometry according to the passed transformation matrix.
  27147. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27148. * The mesh normals are modified accordingly the same transformation.
  27149. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27150. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27151. * Returns the Mesh.
  27152. */
  27153. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27154. // Position
  27155. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27156. return this;
  27157. }
  27158. var submeshes = this.subMeshes.splice(0);
  27159. this._resetPointsArrayCache();
  27160. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27161. var temp = new Array();
  27162. var index;
  27163. for (index = 0; index < data.length; index += 3) {
  27164. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27165. }
  27166. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27167. // Normals
  27168. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27169. return this;
  27170. }
  27171. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27172. temp = [];
  27173. for (index = 0; index < data.length; index += 3) {
  27174. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27175. }
  27176. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27177. // flip faces?
  27178. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27179. this.flipFaces();
  27180. }
  27181. // Restore submeshes
  27182. this.releaseSubMeshes();
  27183. this.subMeshes = submeshes;
  27184. return this;
  27185. };
  27186. /**
  27187. * Modifies the mesh geometry according to its own current World Matrix.
  27188. * The mesh World Matrix is then reset.
  27189. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27190. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27191. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27192. * Returns the Mesh.
  27193. */
  27194. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27195. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27196. this.scaling.copyFromFloats(1, 1, 1);
  27197. this.position.copyFromFloats(0, 0, 0);
  27198. this.rotation.copyFromFloats(0, 0, 0);
  27199. //only if quaternion is already set
  27200. if (this.rotationQuaternion) {
  27201. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27202. }
  27203. this._worldMatrix = BABYLON.Matrix.Identity();
  27204. return this;
  27205. };
  27206. Object.defineProperty(Mesh.prototype, "_positions", {
  27207. // Cache
  27208. get: function () {
  27209. if (this._geometry) {
  27210. return this._geometry._positions;
  27211. }
  27212. return null;
  27213. },
  27214. enumerable: true,
  27215. configurable: true
  27216. });
  27217. Mesh.prototype._resetPointsArrayCache = function () {
  27218. if (this._geometry) {
  27219. this._geometry._resetPointsArrayCache();
  27220. }
  27221. return this;
  27222. };
  27223. Mesh.prototype._generatePointsArray = function () {
  27224. if (this._geometry) {
  27225. return this._geometry._generatePointsArray();
  27226. }
  27227. return false;
  27228. };
  27229. /**
  27230. * Returns a new Mesh object generated from the current mesh properties.
  27231. * This method must not get confused with createInstance().
  27232. * The parameter `name` is a string, the name given to the new mesh.
  27233. * The optional parameter `newParent` can be any Node object (default `null`).
  27234. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27235. * 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.
  27236. */
  27237. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27238. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27239. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27240. };
  27241. /**
  27242. * Disposes the Mesh.
  27243. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27244. * Returns nothing.
  27245. */
  27246. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27247. var _this = this;
  27248. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27249. this.morphTargetManager = null;
  27250. if (this._geometry) {
  27251. this._geometry.releaseForMesh(this, true);
  27252. }
  27253. // Sources
  27254. var meshes = this.getScene().meshes;
  27255. meshes.forEach(function (abstractMesh) {
  27256. var mesh = abstractMesh;
  27257. if (mesh._source && mesh._source === _this) {
  27258. mesh._source = null;
  27259. }
  27260. });
  27261. this._source = null;
  27262. // Instances
  27263. if (this._instancesBuffer) {
  27264. this._instancesBuffer.dispose();
  27265. this._instancesBuffer = null;
  27266. }
  27267. while (this.instances.length) {
  27268. this.instances[0].dispose();
  27269. }
  27270. // Highlight layers.
  27271. var highlightLayers = this.getScene().highlightLayers;
  27272. for (var i = 0; i < highlightLayers.length; i++) {
  27273. var highlightLayer = highlightLayers[i];
  27274. if (highlightLayer) {
  27275. highlightLayer.removeMesh(this);
  27276. highlightLayer.removeExcludedMesh(this);
  27277. }
  27278. }
  27279. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27280. };
  27281. /**
  27282. * Modifies the mesh geometry according to a displacement map.
  27283. * 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.
  27284. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27285. * This method returns nothing.
  27286. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27287. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27288. * 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.
  27289. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27290. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27291. *
  27292. * Returns the Mesh.
  27293. */
  27294. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27295. var _this = this;
  27296. var scene = this.getScene();
  27297. var onload = function (img) {
  27298. // Getting height map data
  27299. var canvas = document.createElement("canvas");
  27300. var context = canvas.getContext("2d");
  27301. var heightMapWidth = img.width;
  27302. var heightMapHeight = img.height;
  27303. canvas.width = heightMapWidth;
  27304. canvas.height = heightMapHeight;
  27305. context.drawImage(img, 0, 0);
  27306. // Create VertexData from map data
  27307. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27308. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27309. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27310. //execute success callback, if set
  27311. if (onSuccess) {
  27312. onSuccess(_this);
  27313. }
  27314. };
  27315. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27316. return this;
  27317. };
  27318. /**
  27319. * Modifies the mesh geometry according to a displacementMap buffer.
  27320. * 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.
  27321. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27322. * This method returns nothing.
  27323. * 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.
  27324. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27325. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27326. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27327. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27328. *
  27329. * Returns the Mesh.
  27330. */
  27331. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27332. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27333. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27334. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27335. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27336. return this;
  27337. }
  27338. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27339. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27340. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27341. var position = BABYLON.Vector3.Zero();
  27342. var normal = BABYLON.Vector3.Zero();
  27343. var uv = BABYLON.Vector2.Zero();
  27344. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27345. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27346. for (var index = 0; index < positions.length; index += 3) {
  27347. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27348. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27349. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27350. // Compute height
  27351. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27352. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27353. var pos = (u + v * heightMapWidth) * 4;
  27354. var r = buffer[pos] / 255.0;
  27355. var g = buffer[pos + 1] / 255.0;
  27356. var b = buffer[pos + 2] / 255.0;
  27357. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27358. normal.normalize();
  27359. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27360. position = position.add(normal);
  27361. position.toArray(positions, index);
  27362. }
  27363. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27364. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27365. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27366. return this;
  27367. };
  27368. /**
  27369. * Modify the mesh to get a flat shading rendering.
  27370. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27371. * This method returns the Mesh.
  27372. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27373. */
  27374. Mesh.prototype.convertToFlatShadedMesh = function () {
  27375. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27376. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27377. var kinds = this.getVerticesDataKinds();
  27378. var vbs = {};
  27379. var data = {};
  27380. var newdata = {};
  27381. var updatableNormals = false;
  27382. var kindIndex;
  27383. var kind;
  27384. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27385. kind = kinds[kindIndex];
  27386. var vertexBuffer = this.getVertexBuffer(kind);
  27387. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27388. updatableNormals = vertexBuffer.isUpdatable();
  27389. kinds.splice(kindIndex, 1);
  27390. kindIndex--;
  27391. continue;
  27392. }
  27393. vbs[kind] = vertexBuffer;
  27394. data[kind] = vbs[kind].getData();
  27395. newdata[kind] = [];
  27396. }
  27397. // Save previous submeshes
  27398. var previousSubmeshes = this.subMeshes.slice(0);
  27399. var indices = this.getIndices();
  27400. var totalIndices = this.getTotalIndices();
  27401. // Generating unique vertices per face
  27402. var index;
  27403. for (index = 0; index < totalIndices; index++) {
  27404. var vertexIndex = indices[index];
  27405. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27406. kind = kinds[kindIndex];
  27407. var stride = vbs[kind].getStrideSize();
  27408. for (var offset = 0; offset < stride; offset++) {
  27409. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27410. }
  27411. }
  27412. }
  27413. // Updating faces & normal
  27414. var normals = [];
  27415. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27416. for (index = 0; index < totalIndices; index += 3) {
  27417. indices[index] = index;
  27418. indices[index + 1] = index + 1;
  27419. indices[index + 2] = index + 2;
  27420. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27421. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27422. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27423. var p1p2 = p1.subtract(p2);
  27424. var p3p2 = p3.subtract(p2);
  27425. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27426. // Store same normals for every vertex
  27427. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27428. normals.push(normal.x);
  27429. normals.push(normal.y);
  27430. normals.push(normal.z);
  27431. }
  27432. }
  27433. this.setIndices(indices);
  27434. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27435. // Updating vertex buffers
  27436. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27437. kind = kinds[kindIndex];
  27438. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27439. }
  27440. // Updating submeshes
  27441. this.releaseSubMeshes();
  27442. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27443. var previousOne = previousSubmeshes[submeshIndex];
  27444. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27445. }
  27446. this.synchronizeInstances();
  27447. return this;
  27448. };
  27449. /**
  27450. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27451. * In other words, more vertices, no more indices and a single bigger VBO.
  27452. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27453. * Returns the Mesh.
  27454. */
  27455. Mesh.prototype.convertToUnIndexedMesh = function () {
  27456. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27457. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27458. var kinds = this.getVerticesDataKinds();
  27459. var vbs = {};
  27460. var data = {};
  27461. var newdata = {};
  27462. var kindIndex;
  27463. var kind;
  27464. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27465. kind = kinds[kindIndex];
  27466. var vertexBuffer = this.getVertexBuffer(kind);
  27467. vbs[kind] = vertexBuffer;
  27468. data[kind] = vbs[kind].getData();
  27469. newdata[kind] = [];
  27470. }
  27471. // Save previous submeshes
  27472. var previousSubmeshes = this.subMeshes.slice(0);
  27473. var indices = this.getIndices();
  27474. var totalIndices = this.getTotalIndices();
  27475. // Generating unique vertices per face
  27476. var index;
  27477. for (index = 0; index < totalIndices; index++) {
  27478. var vertexIndex = indices[index];
  27479. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27480. kind = kinds[kindIndex];
  27481. var stride = vbs[kind].getStrideSize();
  27482. for (var offset = 0; offset < stride; offset++) {
  27483. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27484. }
  27485. }
  27486. }
  27487. // Updating indices
  27488. for (index = 0; index < totalIndices; index += 3) {
  27489. indices[index] = index;
  27490. indices[index + 1] = index + 1;
  27491. indices[index + 2] = index + 2;
  27492. }
  27493. this.setIndices(indices);
  27494. // Updating vertex buffers
  27495. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27496. kind = kinds[kindIndex];
  27497. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27498. }
  27499. // Updating submeshes
  27500. this.releaseSubMeshes();
  27501. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27502. var previousOne = previousSubmeshes[submeshIndex];
  27503. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27504. }
  27505. this._unIndexed = true;
  27506. this.synchronizeInstances();
  27507. return this;
  27508. };
  27509. /**
  27510. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27511. * This method returns the Mesh.
  27512. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27513. */
  27514. Mesh.prototype.flipFaces = function (flipNormals) {
  27515. if (flipNormals === void 0) { flipNormals = false; }
  27516. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27517. var i;
  27518. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27519. for (i = 0; i < vertex_data.normals.length; i++) {
  27520. vertex_data.normals[i] *= -1;
  27521. }
  27522. }
  27523. if (vertex_data.indices) {
  27524. var temp;
  27525. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27526. // reassign indices
  27527. temp = vertex_data.indices[i + 1];
  27528. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27529. vertex_data.indices[i + 2] = temp;
  27530. }
  27531. }
  27532. vertex_data.applyToMesh(this);
  27533. return this;
  27534. };
  27535. // Instances
  27536. /**
  27537. * Creates a new InstancedMesh object from the mesh model.
  27538. * An instance shares the same properties and the same material than its model.
  27539. * Only these properties of each instance can then be set individually :
  27540. * - position
  27541. * - rotation
  27542. * - rotationQuaternion
  27543. * - setPivotMatrix
  27544. * - scaling
  27545. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27546. * Warning : this method is not supported for Line mesh and LineSystem
  27547. */
  27548. Mesh.prototype.createInstance = function (name) {
  27549. return new BABYLON.InstancedMesh(name, this);
  27550. };
  27551. /**
  27552. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27553. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27554. * This method returns the Mesh.
  27555. */
  27556. Mesh.prototype.synchronizeInstances = function () {
  27557. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27558. var instance = this.instances[instanceIndex];
  27559. instance._syncSubMeshes();
  27560. }
  27561. return this;
  27562. };
  27563. /**
  27564. * Simplify the mesh according to the given array of settings.
  27565. * Function will return immediately and will simplify async. It returns the Mesh.
  27566. * @param settings a collection of simplification settings.
  27567. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27568. * @param type the type of simplification to run.
  27569. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27570. */
  27571. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27572. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27573. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27574. this.getScene().simplificationQueue.addTask({
  27575. settings: settings,
  27576. parallelProcessing: parallelProcessing,
  27577. mesh: this,
  27578. simplificationType: simplificationType,
  27579. successCallback: successCallback
  27580. });
  27581. return this;
  27582. };
  27583. /**
  27584. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27585. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27586. * This should be used together with the simplification to avoid disappearing triangles.
  27587. * Returns the Mesh.
  27588. * @param successCallback an optional success callback to be called after the optimization finished.
  27589. */
  27590. Mesh.prototype.optimizeIndices = function (successCallback) {
  27591. var _this = this;
  27592. var indices = this.getIndices();
  27593. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27594. if (!positions || !indices) {
  27595. return this;
  27596. }
  27597. var vectorPositions = new Array();
  27598. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27599. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27600. }
  27601. var dupes = new Array();
  27602. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27603. var realPos = vectorPositions.length - 1 - iteration;
  27604. var testedPosition = vectorPositions[realPos];
  27605. for (var j = 0; j < realPos; ++j) {
  27606. var againstPosition = vectorPositions[j];
  27607. if (testedPosition.equals(againstPosition)) {
  27608. dupes[realPos] = j;
  27609. break;
  27610. }
  27611. }
  27612. }, function () {
  27613. for (var i = 0; i < indices.length; ++i) {
  27614. indices[i] = dupes[indices[i]] || indices[i];
  27615. }
  27616. //indices are now reordered
  27617. var originalSubMeshes = _this.subMeshes.slice(0);
  27618. _this.setIndices(indices);
  27619. _this.subMeshes = originalSubMeshes;
  27620. if (successCallback) {
  27621. successCallback(_this);
  27622. }
  27623. });
  27624. return this;
  27625. };
  27626. Mesh.prototype.serialize = function (serializationObject) {
  27627. serializationObject.name = this.name;
  27628. serializationObject.id = this.id;
  27629. serializationObject.type = this.getClassName();
  27630. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27631. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27632. }
  27633. serializationObject.position = this.position.asArray();
  27634. if (this.rotationQuaternion) {
  27635. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27636. }
  27637. else if (this.rotation) {
  27638. serializationObject.rotation = this.rotation.asArray();
  27639. }
  27640. serializationObject.scaling = this.scaling.asArray();
  27641. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27642. serializationObject.isEnabled = this.isEnabled(false);
  27643. serializationObject.isVisible = this.isVisible;
  27644. serializationObject.infiniteDistance = this.infiniteDistance;
  27645. serializationObject.pickable = this.isPickable;
  27646. serializationObject.receiveShadows = this.receiveShadows;
  27647. serializationObject.billboardMode = this.billboardMode;
  27648. serializationObject.visibility = this.visibility;
  27649. serializationObject.checkCollisions = this.checkCollisions;
  27650. serializationObject.isBlocker = this.isBlocker;
  27651. // Parent
  27652. if (this.parent) {
  27653. serializationObject.parentId = this.parent.id;
  27654. }
  27655. // Geometry
  27656. serializationObject.isUnIndexed = this.isUnIndexed;
  27657. var geometry = this._geometry;
  27658. if (geometry) {
  27659. var geometryId = geometry.id;
  27660. serializationObject.geometryId = geometryId;
  27661. // SubMeshes
  27662. serializationObject.subMeshes = [];
  27663. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27664. var subMesh = this.subMeshes[subIndex];
  27665. serializationObject.subMeshes.push({
  27666. materialIndex: subMesh.materialIndex,
  27667. verticesStart: subMesh.verticesStart,
  27668. verticesCount: subMesh.verticesCount,
  27669. indexStart: subMesh.indexStart,
  27670. indexCount: subMesh.indexCount
  27671. });
  27672. }
  27673. }
  27674. // Material
  27675. if (this.material) {
  27676. serializationObject.materialId = this.material.id;
  27677. }
  27678. else {
  27679. this.material = null;
  27680. }
  27681. // Morph targets
  27682. if (this.morphTargetManager) {
  27683. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27684. }
  27685. // Skeleton
  27686. if (this.skeleton) {
  27687. serializationObject.skeletonId = this.skeleton.id;
  27688. }
  27689. // Physics
  27690. //TODO implement correct serialization for physics impostors.
  27691. var impostor = this.getPhysicsImpostor();
  27692. if (impostor) {
  27693. serializationObject.physicsMass = impostor.getParam("mass");
  27694. serializationObject.physicsFriction = impostor.getParam("friction");
  27695. serializationObject.physicsRestitution = impostor.getParam("mass");
  27696. serializationObject.physicsImpostor = impostor.type;
  27697. }
  27698. // Metadata
  27699. if (this.metadata) {
  27700. serializationObject.metadata = this.metadata;
  27701. }
  27702. // Instances
  27703. serializationObject.instances = [];
  27704. for (var index = 0; index < this.instances.length; index++) {
  27705. var instance = this.instances[index];
  27706. var serializationInstance = {
  27707. name: instance.name,
  27708. id: instance.id,
  27709. position: instance.position.asArray(),
  27710. scaling: instance.scaling.asArray()
  27711. };
  27712. if (instance.rotationQuaternion) {
  27713. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27714. }
  27715. else if (instance.rotation) {
  27716. serializationInstance.rotation = instance.rotation.asArray();
  27717. }
  27718. serializationObject.instances.push(serializationInstance);
  27719. // Animations
  27720. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27721. serializationInstance.ranges = instance.serializeAnimationRanges();
  27722. }
  27723. //
  27724. // Animations
  27725. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27726. serializationObject.ranges = this.serializeAnimationRanges();
  27727. // Layer mask
  27728. serializationObject.layerMask = this.layerMask;
  27729. // Alpha
  27730. serializationObject.alphaIndex = this.alphaIndex;
  27731. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27732. // Overlay
  27733. serializationObject.overlayAlpha = this.overlayAlpha;
  27734. serializationObject.overlayColor = this.overlayColor.asArray();
  27735. serializationObject.renderOverlay = this.renderOverlay;
  27736. // Fog
  27737. serializationObject.applyFog = this.applyFog;
  27738. // Action Manager
  27739. if (this.actionManager) {
  27740. serializationObject.actions = this.actionManager.serialize(this.name);
  27741. }
  27742. };
  27743. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27744. if (!this.geometry) {
  27745. return;
  27746. }
  27747. this._markSubMeshesAsAttributesDirty();
  27748. var morphTargetManager = this._morphTargetManager;
  27749. if (morphTargetManager && morphTargetManager.vertexCount) {
  27750. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27751. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27752. this.morphTargetManager = null;
  27753. return;
  27754. }
  27755. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27756. var morphTarget = morphTargetManager.getActiveTarget(index);
  27757. var positions = morphTarget.getPositions();
  27758. if (!positions) {
  27759. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27760. return;
  27761. }
  27762. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27763. var normals = morphTarget.getNormals();
  27764. if (normals) {
  27765. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27766. }
  27767. var tangents = morphTarget.getTangents();
  27768. if (tangents) {
  27769. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27770. }
  27771. }
  27772. }
  27773. else {
  27774. var index = 0;
  27775. // Positions
  27776. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27777. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27778. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27779. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27780. }
  27781. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27782. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27783. }
  27784. index++;
  27785. }
  27786. }
  27787. };
  27788. // Statics
  27789. /**
  27790. * Returns a new Mesh object parsed from the source provided.
  27791. * The parameter `parsedMesh` is the source.
  27792. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27793. */
  27794. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27795. var mesh;
  27796. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27797. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27798. }
  27799. else {
  27800. mesh = new Mesh(parsedMesh.name, scene);
  27801. }
  27802. mesh.id = parsedMesh.id;
  27803. if (BABYLON.Tags) {
  27804. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27805. }
  27806. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27807. if (parsedMesh.metadata !== undefined) {
  27808. mesh.metadata = parsedMesh.metadata;
  27809. }
  27810. if (parsedMesh.rotationQuaternion) {
  27811. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27812. }
  27813. else if (parsedMesh.rotation) {
  27814. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27815. }
  27816. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27817. if (parsedMesh.localMatrix) {
  27818. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27819. }
  27820. else if (parsedMesh.pivotMatrix) {
  27821. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27822. }
  27823. mesh.setEnabled(parsedMesh.isEnabled);
  27824. mesh.isVisible = parsedMesh.isVisible;
  27825. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27826. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27827. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27828. if (parsedMesh.applyFog !== undefined) {
  27829. mesh.applyFog = parsedMesh.applyFog;
  27830. }
  27831. if (parsedMesh.pickable !== undefined) {
  27832. mesh.isPickable = parsedMesh.pickable;
  27833. }
  27834. if (parsedMesh.alphaIndex !== undefined) {
  27835. mesh.alphaIndex = parsedMesh.alphaIndex;
  27836. }
  27837. mesh.receiveShadows = parsedMesh.receiveShadows;
  27838. mesh.billboardMode = parsedMesh.billboardMode;
  27839. if (parsedMesh.visibility !== undefined) {
  27840. mesh.visibility = parsedMesh.visibility;
  27841. }
  27842. mesh.checkCollisions = parsedMesh.checkCollisions;
  27843. if (parsedMesh.isBlocker !== undefined) {
  27844. mesh.isBlocker = parsedMesh.isBlocker;
  27845. }
  27846. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27847. // freezeWorldMatrix
  27848. if (parsedMesh.freezeWorldMatrix) {
  27849. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27850. }
  27851. // Parent
  27852. if (parsedMesh.parentId) {
  27853. mesh._waitingParentId = parsedMesh.parentId;
  27854. }
  27855. // Actions
  27856. if (parsedMesh.actions !== undefined) {
  27857. mesh._waitingActions = parsedMesh.actions;
  27858. }
  27859. // Overlay
  27860. if (parsedMesh.overlayAlpha !== undefined) {
  27861. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27862. }
  27863. if (parsedMesh.overlayColor !== undefined) {
  27864. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27865. }
  27866. if (parsedMesh.renderOverlay !== undefined) {
  27867. mesh.renderOverlay = parsedMesh.renderOverlay;
  27868. }
  27869. // Geometry
  27870. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27871. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27872. if (parsedMesh.delayLoadingFile) {
  27873. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27874. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27875. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27876. if (parsedMesh._binaryInfo) {
  27877. mesh._binaryInfo = parsedMesh._binaryInfo;
  27878. }
  27879. mesh._delayInfo = [];
  27880. if (parsedMesh.hasUVs) {
  27881. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27882. }
  27883. if (parsedMesh.hasUVs2) {
  27884. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27885. }
  27886. if (parsedMesh.hasUVs3) {
  27887. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27888. }
  27889. if (parsedMesh.hasUVs4) {
  27890. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27891. }
  27892. if (parsedMesh.hasUVs5) {
  27893. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27894. }
  27895. if (parsedMesh.hasUVs6) {
  27896. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27897. }
  27898. if (parsedMesh.hasColors) {
  27899. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27900. }
  27901. if (parsedMesh.hasMatricesIndices) {
  27902. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27903. }
  27904. if (parsedMesh.hasMatricesWeights) {
  27905. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27906. }
  27907. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27908. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27909. mesh._checkDelayState();
  27910. }
  27911. }
  27912. else {
  27913. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27914. }
  27915. // Material
  27916. if (parsedMesh.materialId) {
  27917. mesh.setMaterialByID(parsedMesh.materialId);
  27918. }
  27919. else {
  27920. mesh.material = null;
  27921. }
  27922. // Morph targets
  27923. if (parsedMesh.morphTargetManagerId > -1) {
  27924. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27925. }
  27926. // Skeleton
  27927. if (parsedMesh.skeletonId > -1) {
  27928. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27929. if (parsedMesh.numBoneInfluencers) {
  27930. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27931. }
  27932. }
  27933. // Animations
  27934. if (parsedMesh.animations) {
  27935. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27936. var parsedAnimation = parsedMesh.animations[animationIndex];
  27937. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27938. }
  27939. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27940. }
  27941. if (parsedMesh.autoAnimate) {
  27942. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27943. }
  27944. // Layer Mask
  27945. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27946. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27947. }
  27948. else {
  27949. mesh.layerMask = 0x0FFFFFFF;
  27950. }
  27951. // Physics
  27952. if (parsedMesh.physicsImpostor) {
  27953. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27954. mass: parsedMesh.physicsMass,
  27955. friction: parsedMesh.physicsFriction,
  27956. restitution: parsedMesh.physicsRestitution
  27957. }, scene);
  27958. }
  27959. // Instances
  27960. if (parsedMesh.instances) {
  27961. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27962. var parsedInstance = parsedMesh.instances[index];
  27963. var instance = mesh.createInstance(parsedInstance.name);
  27964. if (parsedInstance.id) {
  27965. instance.id = parsedInstance.id;
  27966. }
  27967. if (BABYLON.Tags) {
  27968. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27969. }
  27970. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27971. if (parsedInstance.parentId) {
  27972. instance._waitingParentId = parsedInstance.parentId;
  27973. }
  27974. if (parsedInstance.rotationQuaternion) {
  27975. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27976. }
  27977. else if (parsedInstance.rotation) {
  27978. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27979. }
  27980. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27981. instance.checkCollisions = mesh.checkCollisions;
  27982. if (parsedMesh.animations) {
  27983. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27984. parsedAnimation = parsedMesh.animations[animationIndex];
  27985. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27986. }
  27987. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27988. }
  27989. }
  27990. }
  27991. return mesh;
  27992. };
  27993. /**
  27994. * Creates a ribbon mesh.
  27995. * Please consider using the same method from the MeshBuilder class instead.
  27996. * 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.
  27997. *
  27998. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27999. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28000. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28001. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28002. * 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.
  28003. * 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.
  28004. * 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
  28005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28006. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28008. */
  28009. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28010. if (closeArray === void 0) { closeArray = false; }
  28011. if (updatable === void 0) { updatable = false; }
  28012. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28013. pathArray: pathArray,
  28014. closeArray: closeArray,
  28015. closePath: closePath,
  28016. offset: offset,
  28017. updatable: updatable,
  28018. sideOrientation: sideOrientation,
  28019. instance: instance
  28020. }, scene);
  28021. };
  28022. /**
  28023. * Creates a plane polygonal mesh. By default, this is a disc.
  28024. * Please consider using the same method from the MeshBuilder class instead.
  28025. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28026. * 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.
  28027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28030. */
  28031. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28032. if (scene === void 0) { scene = null; }
  28033. var options = {
  28034. radius: radius,
  28035. tessellation: tessellation,
  28036. sideOrientation: sideOrientation,
  28037. updatable: updatable
  28038. };
  28039. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28040. };
  28041. /**
  28042. * Creates a box mesh.
  28043. * Please consider using the same method from the MeshBuilder class instead.
  28044. * The parameter `size` sets the size (float) of each box side (default 1).
  28045. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28046. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28047. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28048. */
  28049. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28050. if (scene === void 0) { scene = null; }
  28051. var options = {
  28052. size: size,
  28053. sideOrientation: sideOrientation,
  28054. updatable: updatable
  28055. };
  28056. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28057. };
  28058. /**
  28059. * Creates a sphere mesh.
  28060. * Please consider using the same method from the MeshBuilder class instead.
  28061. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28062. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28064. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28066. */
  28067. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28068. var options = {
  28069. segments: segments,
  28070. diameterX: diameter,
  28071. diameterY: diameter,
  28072. diameterZ: diameter,
  28073. sideOrientation: sideOrientation,
  28074. updatable: updatable
  28075. };
  28076. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28077. };
  28078. /**
  28079. * Creates a cylinder or a cone mesh.
  28080. * Please consider using the same method from the MeshBuilder class instead.
  28081. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28082. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28083. * 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.
  28084. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28085. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28087. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28089. */
  28090. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28091. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28092. if (scene !== undefined) {
  28093. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28094. updatable = scene;
  28095. }
  28096. scene = subdivisions;
  28097. subdivisions = 1;
  28098. }
  28099. var options = {
  28100. height: height,
  28101. diameterTop: diameterTop,
  28102. diameterBottom: diameterBottom,
  28103. tessellation: tessellation,
  28104. subdivisions: subdivisions,
  28105. sideOrientation: sideOrientation,
  28106. updatable: updatable
  28107. };
  28108. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28109. };
  28110. // Torus (Code from SharpDX.org)
  28111. /**
  28112. * Creates a torus mesh.
  28113. * Please consider using the same method from the MeshBuilder class instead.
  28114. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28115. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28116. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28117. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28118. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28120. */
  28121. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28122. var options = {
  28123. diameter: diameter,
  28124. thickness: thickness,
  28125. tessellation: tessellation,
  28126. sideOrientation: sideOrientation,
  28127. updatable: updatable
  28128. };
  28129. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28130. };
  28131. /**
  28132. * Creates a torus knot mesh.
  28133. * Please consider using the same method from the MeshBuilder class instead.
  28134. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28135. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28136. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28137. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28139. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28141. */
  28142. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28143. var options = {
  28144. radius: radius,
  28145. tube: tube,
  28146. radialSegments: radialSegments,
  28147. tubularSegments: tubularSegments,
  28148. p: p,
  28149. q: q,
  28150. sideOrientation: sideOrientation,
  28151. updatable: updatable
  28152. };
  28153. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28154. };
  28155. /**
  28156. * Creates a line mesh.
  28157. * Please consider using the same method from the MeshBuilder class instead.
  28158. * 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.
  28159. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28160. * The parameter `points` is an array successive Vector3.
  28161. * 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
  28162. * When updating an instance, remember that only point positions can change, not the number of points.
  28163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28164. */
  28165. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28166. if (scene === void 0) { scene = null; }
  28167. if (updatable === void 0) { updatable = false; }
  28168. if (instance === void 0) { instance = null; }
  28169. var options = {
  28170. points: points,
  28171. updatable: updatable,
  28172. instance: instance
  28173. };
  28174. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28175. };
  28176. /**
  28177. * Creates a dashed line mesh.
  28178. * Please consider using the same method from the MeshBuilder class instead.
  28179. * 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.
  28180. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28181. * The parameter `points` is an array successive Vector3.
  28182. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28183. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28184. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28185. * 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
  28186. * When updating an instance, remember that only point positions can change, not the number of points.
  28187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28188. */
  28189. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28190. if (scene === void 0) { scene = null; }
  28191. var options = {
  28192. points: points,
  28193. dashSize: dashSize,
  28194. gapSize: gapSize,
  28195. dashNb: dashNb,
  28196. updatable: updatable,
  28197. instance: instance
  28198. };
  28199. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28200. };
  28201. /**
  28202. * Creates a polygon mesh.
  28203. * Please consider using the same method from the MeshBuilder class instead.
  28204. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28205. * 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.
  28206. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28207. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28208. * Remember you can only change the shape positions, not their number when updating a polygon.
  28209. */
  28210. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28211. var options = {
  28212. shape: shape,
  28213. holes: holes,
  28214. updatable: updatable,
  28215. sideOrientation: sideOrientation
  28216. };
  28217. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28218. };
  28219. /**
  28220. * Creates an extruded polygon mesh, with depth in the Y direction.
  28221. * Please consider using the same method from the MeshBuilder class instead.
  28222. */
  28223. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28224. var options = {
  28225. shape: shape,
  28226. holes: holes,
  28227. depth: depth,
  28228. updatable: updatable,
  28229. sideOrientation: sideOrientation
  28230. };
  28231. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28232. };
  28233. /**
  28234. * Creates an extruded shape mesh.
  28235. * 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.
  28236. * Please consider using the same method from the MeshBuilder class instead.
  28237. *
  28238. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28239. * 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
  28240. * extruded along the Z axis.
  28241. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28242. * 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.
  28243. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28244. * 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
  28245. * 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
  28246. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28250. */
  28251. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28252. if (scene === void 0) { scene = null; }
  28253. var options = {
  28254. shape: shape,
  28255. path: path,
  28256. scale: scale,
  28257. rotation: rotation,
  28258. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28259. sideOrientation: sideOrientation,
  28260. instance: instance,
  28261. updatable: updatable
  28262. };
  28263. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28264. };
  28265. /**
  28266. * Creates an custom extruded shape mesh.
  28267. * 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.
  28268. * Please consider using the same method from the MeshBuilder class instead.
  28269. *
  28270. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28271. * 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
  28272. * extruded along the Z axis.
  28273. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28274. * 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
  28275. * and the distance of this point from the begining of the path :
  28276. * ```javascript
  28277. * var rotationFunction = function(i, distance) {
  28278. * // do things
  28279. * return rotationValue; }
  28280. * ```
  28281. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28282. * 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
  28283. * and the distance of this point from the begining of the path :
  28284. * ```javascript
  28285. * var scaleFunction = function(i, distance) {
  28286. * // do things
  28287. * return scaleValue;}
  28288. * ```
  28289. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28290. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28291. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28292. * 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
  28293. * 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
  28294. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28295. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28296. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28297. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28298. */
  28299. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28300. var options = {
  28301. shape: shape,
  28302. path: path,
  28303. scaleFunction: scaleFunction,
  28304. rotationFunction: rotationFunction,
  28305. ribbonCloseArray: ribbonCloseArray,
  28306. ribbonClosePath: ribbonClosePath,
  28307. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28308. sideOrientation: sideOrientation,
  28309. instance: instance,
  28310. updatable: updatable
  28311. };
  28312. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28313. };
  28314. /**
  28315. * Creates lathe mesh.
  28316. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28317. * Please consider using the same method from the MeshBuilder class instead.
  28318. * 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
  28319. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28320. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28321. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28322. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28323. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28325. */
  28326. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28327. var options = {
  28328. shape: shape,
  28329. radius: radius,
  28330. tessellation: tessellation,
  28331. sideOrientation: sideOrientation,
  28332. updatable: updatable
  28333. };
  28334. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28335. };
  28336. /**
  28337. * Creates a plane mesh.
  28338. * Please consider using the same method from the MeshBuilder class instead.
  28339. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28341. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28343. */
  28344. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28345. var options = {
  28346. size: size,
  28347. width: size,
  28348. height: size,
  28349. sideOrientation: sideOrientation,
  28350. updatable: updatable
  28351. };
  28352. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28353. };
  28354. /**
  28355. * Creates a ground mesh.
  28356. * Please consider using the same method from the MeshBuilder class instead.
  28357. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28358. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28360. */
  28361. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28362. var options = {
  28363. width: width,
  28364. height: height,
  28365. subdivisions: subdivisions,
  28366. updatable: updatable
  28367. };
  28368. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28369. };
  28370. /**
  28371. * Creates a tiled ground mesh.
  28372. * Please consider using the same method from the MeshBuilder class instead.
  28373. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28374. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28375. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28376. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28377. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28378. * numbers of subdivisions on the ground width and height of each tile.
  28379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28380. */
  28381. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28382. var options = {
  28383. xmin: xmin,
  28384. zmin: zmin,
  28385. xmax: xmax,
  28386. zmax: zmax,
  28387. subdivisions: subdivisions,
  28388. precision: precision,
  28389. updatable: updatable
  28390. };
  28391. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28392. };
  28393. /**
  28394. * Creates a ground mesh from a height map.
  28395. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28396. * Please consider using the same method from the MeshBuilder class instead.
  28397. * The parameter `url` sets the URL of the height map image resource.
  28398. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28399. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28400. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28401. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28402. * 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).
  28403. * This function is passed the newly built mesh :
  28404. * ```javascript
  28405. * function(mesh) { // do things
  28406. * return; }
  28407. * ```
  28408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28409. */
  28410. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28411. var options = {
  28412. width: width,
  28413. height: height,
  28414. subdivisions: subdivisions,
  28415. minHeight: minHeight,
  28416. maxHeight: maxHeight,
  28417. updatable: updatable,
  28418. onReady: onReady
  28419. };
  28420. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28421. };
  28422. /**
  28423. * Creates a tube mesh.
  28424. * 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.
  28425. * Please consider using the same method from the MeshBuilder class instead.
  28426. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28427. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28428. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28429. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28430. * 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.
  28431. * It must return a radius value (positive float) :
  28432. * ```javascript
  28433. * var radiusFunction = function(i, distance) {
  28434. * // do things
  28435. * return radius; }
  28436. * ```
  28437. * 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
  28438. * 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
  28439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28442. */
  28443. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28444. var options = {
  28445. path: path,
  28446. radius: radius,
  28447. tessellation: tessellation,
  28448. radiusFunction: radiusFunction,
  28449. arc: 1,
  28450. cap: cap,
  28451. updatable: updatable,
  28452. sideOrientation: sideOrientation,
  28453. instance: instance
  28454. };
  28455. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28456. };
  28457. /**
  28458. * Creates a polyhedron mesh.
  28459. * Please consider using the same method from the MeshBuilder class instead.
  28460. * 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
  28461. * to choose the wanted type.
  28462. * The parameter `size` (positive float, default 1) sets the polygon size.
  28463. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28464. * 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`.
  28465. * 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
  28466. * 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)`).
  28467. * 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
  28468. * 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.
  28469. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28470. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28472. */
  28473. Mesh.CreatePolyhedron = function (name, options, scene) {
  28474. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28475. };
  28476. /**
  28477. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28478. * Please consider using the same method from the MeshBuilder class instead.
  28479. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28480. * 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`).
  28481. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28482. * 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.
  28483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28486. */
  28487. Mesh.CreateIcoSphere = function (name, options, scene) {
  28488. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28489. };
  28490. /**
  28491. * Creates a decal mesh.
  28492. * Please consider using the same method from the MeshBuilder class instead.
  28493. * 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.
  28494. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28495. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28496. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28497. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28498. */
  28499. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28500. var options = {
  28501. position: position,
  28502. normal: normal,
  28503. size: size,
  28504. angle: angle
  28505. };
  28506. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28507. };
  28508. // Skeletons
  28509. /**
  28510. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28511. */
  28512. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28513. if (!this._sourcePositions) {
  28514. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28515. if (!source) {
  28516. return this._sourcePositions;
  28517. }
  28518. this._sourcePositions = new Float32Array(source);
  28519. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28520. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28521. }
  28522. }
  28523. return this._sourcePositions;
  28524. };
  28525. /**
  28526. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28527. */
  28528. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28529. if (!this._sourceNormals) {
  28530. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28531. if (!source) {
  28532. return this._sourceNormals;
  28533. }
  28534. this._sourceNormals = new Float32Array(source);
  28535. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28536. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28537. }
  28538. }
  28539. return this._sourceNormals;
  28540. };
  28541. /**
  28542. * Updates the vertex buffer by applying transformation from the bones.
  28543. * Returns the Mesh.
  28544. *
  28545. * @param {skeleton} skeleton to apply
  28546. */
  28547. Mesh.prototype.applySkeleton = function (skeleton) {
  28548. if (!this.geometry) {
  28549. return this;
  28550. }
  28551. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28552. return this;
  28553. }
  28554. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28555. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28556. return this;
  28557. }
  28558. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28559. return this;
  28560. }
  28561. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28562. return this;
  28563. }
  28564. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28565. return this;
  28566. }
  28567. if (!this._sourcePositions) {
  28568. var submeshes = this.subMeshes.slice();
  28569. this.setPositionsForCPUSkinning();
  28570. this.subMeshes = submeshes;
  28571. }
  28572. if (!this._sourceNormals) {
  28573. this.setNormalsForCPUSkinning();
  28574. }
  28575. // positionsData checks for not being Float32Array will only pass at most once
  28576. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28577. if (!positionsData) {
  28578. return this;
  28579. }
  28580. if (!(positionsData instanceof Float32Array)) {
  28581. positionsData = new Float32Array(positionsData);
  28582. }
  28583. // normalsData checks for not being Float32Array will only pass at most once
  28584. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28585. if (!normalsData) {
  28586. return this;
  28587. }
  28588. if (!(normalsData instanceof Float32Array)) {
  28589. normalsData = new Float32Array(normalsData);
  28590. }
  28591. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28592. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28593. if (!matricesWeightsData || !matricesIndicesData) {
  28594. return this;
  28595. }
  28596. var needExtras = this.numBoneInfluencers > 4;
  28597. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28598. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28599. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28600. var tempVector3 = BABYLON.Vector3.Zero();
  28601. var finalMatrix = new BABYLON.Matrix();
  28602. var tempMatrix = new BABYLON.Matrix();
  28603. var matWeightIdx = 0;
  28604. var inf;
  28605. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28606. var weight;
  28607. for (inf = 0; inf < 4; inf++) {
  28608. weight = matricesWeightsData[matWeightIdx + inf];
  28609. if (weight > 0) {
  28610. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28611. finalMatrix.addToSelf(tempMatrix);
  28612. }
  28613. else
  28614. break;
  28615. }
  28616. if (needExtras) {
  28617. for (inf = 0; inf < 4; inf++) {
  28618. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28619. if (weight > 0) {
  28620. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28621. finalMatrix.addToSelf(tempMatrix);
  28622. }
  28623. else
  28624. break;
  28625. }
  28626. }
  28627. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28628. tempVector3.toArray(positionsData, index);
  28629. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28630. tempVector3.toArray(normalsData, index);
  28631. finalMatrix.reset();
  28632. }
  28633. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28634. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28635. return this;
  28636. };
  28637. // Tools
  28638. /**
  28639. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28640. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28641. */
  28642. Mesh.MinMax = function (meshes) {
  28643. var minVector = null;
  28644. var maxVector = null;
  28645. meshes.forEach(function (mesh, index, array) {
  28646. var boundingInfo = mesh.getBoundingInfo();
  28647. var boundingBox = boundingInfo.boundingBox;
  28648. if (!minVector || !maxVector) {
  28649. minVector = boundingBox.minimumWorld;
  28650. maxVector = boundingBox.maximumWorld;
  28651. }
  28652. else {
  28653. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28654. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28655. }
  28656. });
  28657. if (!minVector || !maxVector) {
  28658. return {
  28659. min: BABYLON.Vector3.Zero(),
  28660. max: BABYLON.Vector3.Zero()
  28661. };
  28662. }
  28663. return {
  28664. min: minVector,
  28665. max: maxVector
  28666. };
  28667. };
  28668. /**
  28669. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28670. */
  28671. Mesh.Center = function (meshesOrMinMaxVector) {
  28672. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28673. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28674. };
  28675. /**
  28676. * Merge the array of meshes into a single mesh for performance reasons.
  28677. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28678. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28679. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28680. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28681. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28682. */
  28683. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28684. if (disposeSource === void 0) { disposeSource = true; }
  28685. var index;
  28686. if (!allow32BitsIndices) {
  28687. var totalVertices = 0;
  28688. // Counting vertices
  28689. for (index = 0; index < meshes.length; index++) {
  28690. if (meshes[index]) {
  28691. totalVertices += meshes[index].getTotalVertices();
  28692. if (totalVertices > 65536) {
  28693. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28694. return null;
  28695. }
  28696. }
  28697. }
  28698. }
  28699. // Merge
  28700. var vertexData = null;
  28701. var otherVertexData;
  28702. var indiceArray = new Array();
  28703. var source = null;
  28704. for (index = 0; index < meshes.length; index++) {
  28705. if (meshes[index]) {
  28706. meshes[index].computeWorldMatrix(true);
  28707. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28708. otherVertexData.transform(meshes[index].getWorldMatrix());
  28709. if (vertexData) {
  28710. vertexData.merge(otherVertexData);
  28711. }
  28712. else {
  28713. vertexData = otherVertexData;
  28714. source = meshes[index];
  28715. }
  28716. if (subdivideWithSubMeshes) {
  28717. indiceArray.push(meshes[index].getTotalIndices());
  28718. }
  28719. }
  28720. }
  28721. source = source;
  28722. if (!meshSubclass) {
  28723. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28724. }
  28725. vertexData.applyToMesh(meshSubclass);
  28726. // Setting properties
  28727. meshSubclass.material = source.material;
  28728. meshSubclass.checkCollisions = source.checkCollisions;
  28729. // Cleaning
  28730. if (disposeSource) {
  28731. for (index = 0; index < meshes.length; index++) {
  28732. if (meshes[index]) {
  28733. meshes[index].dispose();
  28734. }
  28735. }
  28736. }
  28737. // Subdivide
  28738. if (subdivideWithSubMeshes) {
  28739. //-- Suppresions du submesh global
  28740. meshSubclass.releaseSubMeshes();
  28741. index = 0;
  28742. var offset = 0;
  28743. //-- aplique la subdivision en fonction du tableau d'indices
  28744. while (index < indiceArray.length) {
  28745. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28746. offset += indiceArray[index];
  28747. index++;
  28748. }
  28749. }
  28750. return meshSubclass;
  28751. };
  28752. // Consts
  28753. Mesh._FRONTSIDE = 0;
  28754. Mesh._BACKSIDE = 1;
  28755. Mesh._DOUBLESIDE = 2;
  28756. Mesh._DEFAULTSIDE = 0;
  28757. Mesh._NO_CAP = 0;
  28758. Mesh._CAP_START = 1;
  28759. Mesh._CAP_END = 2;
  28760. Mesh._CAP_ALL = 3;
  28761. return Mesh;
  28762. }(BABYLON.AbstractMesh));
  28763. BABYLON.Mesh = Mesh;
  28764. })(BABYLON || (BABYLON = {}));
  28765. //# sourceMappingURL=babylon.mesh.js.map
  28766. var BABYLON;
  28767. (function (BABYLON) {
  28768. var BaseSubMesh = /** @class */ (function () {
  28769. function BaseSubMesh() {
  28770. }
  28771. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28772. get: function () {
  28773. return this._materialEffect;
  28774. },
  28775. enumerable: true,
  28776. configurable: true
  28777. });
  28778. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28779. if (defines === void 0) { defines = null; }
  28780. if (this._materialEffect === effect) {
  28781. if (!effect) {
  28782. this._materialDefines = null;
  28783. }
  28784. return;
  28785. }
  28786. this._materialDefines = defines;
  28787. this._materialEffect = effect;
  28788. };
  28789. return BaseSubMesh;
  28790. }());
  28791. BABYLON.BaseSubMesh = BaseSubMesh;
  28792. var SubMesh = /** @class */ (function (_super) {
  28793. __extends(SubMesh, _super);
  28794. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28795. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28796. var _this = _super.call(this) || this;
  28797. _this.materialIndex = materialIndex;
  28798. _this.verticesStart = verticesStart;
  28799. _this.verticesCount = verticesCount;
  28800. _this.indexStart = indexStart;
  28801. _this.indexCount = indexCount;
  28802. _this._renderId = 0;
  28803. _this._mesh = mesh;
  28804. _this._renderingMesh = renderingMesh || mesh;
  28805. mesh.subMeshes.push(_this);
  28806. _this._trianglePlanes = [];
  28807. _this._id = mesh.subMeshes.length - 1;
  28808. if (createBoundingBox) {
  28809. _this.refreshBoundingInfo();
  28810. mesh.computeWorldMatrix(true);
  28811. }
  28812. return _this;
  28813. }
  28814. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28815. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28816. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28817. };
  28818. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28819. get: function () {
  28820. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28821. },
  28822. enumerable: true,
  28823. configurable: true
  28824. });
  28825. /**
  28826. * Returns the submesh BoudingInfo object.
  28827. */
  28828. SubMesh.prototype.getBoundingInfo = function () {
  28829. if (this.IsGlobal) {
  28830. return this._mesh.getBoundingInfo();
  28831. }
  28832. return this._boundingInfo;
  28833. };
  28834. /**
  28835. * Sets the submesh BoundingInfo.
  28836. * Return the SubMesh.
  28837. */
  28838. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28839. this._boundingInfo = boundingInfo;
  28840. return this;
  28841. };
  28842. /**
  28843. * Returns the mesh of the current submesh.
  28844. */
  28845. SubMesh.prototype.getMesh = function () {
  28846. return this._mesh;
  28847. };
  28848. /**
  28849. * Returns the rendering mesh of the submesh.
  28850. */
  28851. SubMesh.prototype.getRenderingMesh = function () {
  28852. return this._renderingMesh;
  28853. };
  28854. /**
  28855. * Returns the submesh material.
  28856. */
  28857. SubMesh.prototype.getMaterial = function () {
  28858. var rootMaterial = this._renderingMesh.material;
  28859. if (rootMaterial === null || rootMaterial === undefined) {
  28860. return this._mesh.getScene().defaultMaterial;
  28861. }
  28862. else if (rootMaterial.getSubMaterial) {
  28863. var multiMaterial = rootMaterial;
  28864. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28865. if (this._currentMaterial !== effectiveMaterial) {
  28866. this._currentMaterial = effectiveMaterial;
  28867. this._materialDefines = null;
  28868. }
  28869. return effectiveMaterial;
  28870. }
  28871. return rootMaterial;
  28872. };
  28873. // Methods
  28874. /**
  28875. * Sets a new updated BoundingInfo object to the submesh.
  28876. * Returns the SubMesh.
  28877. */
  28878. SubMesh.prototype.refreshBoundingInfo = function () {
  28879. this._lastColliderWorldVertices = null;
  28880. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28881. return this;
  28882. }
  28883. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28884. if (!data) {
  28885. this._boundingInfo = this._mesh.getBoundingInfo();
  28886. return this;
  28887. }
  28888. var indices = this._renderingMesh.getIndices();
  28889. var extend;
  28890. //is this the only submesh?
  28891. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28892. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28893. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28894. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28895. }
  28896. else {
  28897. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28898. }
  28899. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28900. return this;
  28901. };
  28902. SubMesh.prototype._checkCollision = function (collider) {
  28903. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28904. return boundingInfo._checkCollision(collider);
  28905. };
  28906. /**
  28907. * Updates the submesh BoundingInfo.
  28908. * Returns the Submesh.
  28909. */
  28910. SubMesh.prototype.updateBoundingInfo = function (world) {
  28911. var boundingInfo = this.getBoundingInfo();
  28912. if (!boundingInfo) {
  28913. this.refreshBoundingInfo();
  28914. boundingInfo = this.getBoundingInfo();
  28915. }
  28916. boundingInfo.update(world);
  28917. return this;
  28918. };
  28919. /**
  28920. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28921. * Boolean returned.
  28922. */
  28923. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28924. var boundingInfo = this.getBoundingInfo();
  28925. if (!boundingInfo) {
  28926. return false;
  28927. }
  28928. return boundingInfo.isInFrustum(frustumPlanes);
  28929. };
  28930. /**
  28931. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28932. * Boolean returned.
  28933. */
  28934. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28935. var boundingInfo = this.getBoundingInfo();
  28936. if (!boundingInfo) {
  28937. return false;
  28938. }
  28939. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28940. };
  28941. /**
  28942. * Renders the submesh.
  28943. * Returns it.
  28944. */
  28945. SubMesh.prototype.render = function (enableAlphaMode) {
  28946. this._renderingMesh.render(this, enableAlphaMode);
  28947. return this;
  28948. };
  28949. /**
  28950. * Returns a new Index Buffer.
  28951. * Type returned : WebGLBuffer.
  28952. */
  28953. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28954. if (!this._linesIndexBuffer) {
  28955. var linesIndices = [];
  28956. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28957. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28958. }
  28959. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28960. this.linesIndexCount = linesIndices.length;
  28961. }
  28962. return this._linesIndexBuffer;
  28963. };
  28964. /**
  28965. * True is the passed Ray intersects the submesh bounding box.
  28966. * Boolean returned.
  28967. */
  28968. SubMesh.prototype.canIntersects = function (ray) {
  28969. var boundingInfo = this.getBoundingInfo();
  28970. if (!boundingInfo) {
  28971. return false;
  28972. }
  28973. return ray.intersectsBox(boundingInfo.boundingBox);
  28974. };
  28975. /**
  28976. * Returns an object IntersectionInfo.
  28977. */
  28978. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28979. var intersectInfo = null;
  28980. // LineMesh first as it's also a Mesh...
  28981. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28982. var lineMesh = this._mesh;
  28983. // Line test
  28984. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28985. var p0 = positions[indices[index]];
  28986. var p1 = positions[indices[index + 1]];
  28987. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28988. if (length < 0) {
  28989. continue;
  28990. }
  28991. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28992. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28993. if (fastCheck) {
  28994. break;
  28995. }
  28996. }
  28997. }
  28998. }
  28999. else {
  29000. // Triangles test
  29001. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29002. var p0 = positions[indices[index]];
  29003. var p1 = positions[indices[index + 1]];
  29004. var p2 = positions[indices[index + 2]];
  29005. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29006. if (currentIntersectInfo) {
  29007. if (currentIntersectInfo.distance < 0) {
  29008. continue;
  29009. }
  29010. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29011. intersectInfo = currentIntersectInfo;
  29012. intersectInfo.faceId = index / 3;
  29013. if (fastCheck) {
  29014. break;
  29015. }
  29016. }
  29017. }
  29018. }
  29019. }
  29020. return intersectInfo;
  29021. };
  29022. SubMesh.prototype._rebuild = function () {
  29023. if (this._linesIndexBuffer) {
  29024. this._linesIndexBuffer = null;
  29025. }
  29026. };
  29027. // Clone
  29028. /**
  29029. * Creates a new Submesh from the passed Mesh.
  29030. */
  29031. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29032. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29033. if (!this.IsGlobal) {
  29034. var boundingInfo = this.getBoundingInfo();
  29035. if (!boundingInfo) {
  29036. return result;
  29037. }
  29038. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29039. }
  29040. return result;
  29041. };
  29042. // Dispose
  29043. /**
  29044. * Disposes the Submesh.
  29045. * Returns nothing.
  29046. */
  29047. SubMesh.prototype.dispose = function () {
  29048. if (this._linesIndexBuffer) {
  29049. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29050. this._linesIndexBuffer = null;
  29051. }
  29052. // Remove from mesh
  29053. var index = this._mesh.subMeshes.indexOf(this);
  29054. this._mesh.subMeshes.splice(index, 1);
  29055. };
  29056. // Statics
  29057. /**
  29058. * Creates a new Submesh from the passed parameters :
  29059. * - materialIndex (integer) : the index of the main mesh material.
  29060. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29061. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29062. * - mesh (Mesh) : the main mesh to create the submesh from.
  29063. * - renderingMesh (optional Mesh) : rendering mesh.
  29064. */
  29065. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29066. var minVertexIndex = Number.MAX_VALUE;
  29067. var maxVertexIndex = -Number.MAX_VALUE;
  29068. renderingMesh = (renderingMesh || mesh);
  29069. var indices = renderingMesh.getIndices();
  29070. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29071. var vertexIndex = indices[index];
  29072. if (vertexIndex < minVertexIndex)
  29073. minVertexIndex = vertexIndex;
  29074. if (vertexIndex > maxVertexIndex)
  29075. maxVertexIndex = vertexIndex;
  29076. }
  29077. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29078. };
  29079. return SubMesh;
  29080. }(BaseSubMesh));
  29081. BABYLON.SubMesh = SubMesh;
  29082. })(BABYLON || (BABYLON = {}));
  29083. //# sourceMappingURL=babylon.subMesh.js.map
  29084. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29085. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29086. s = arguments[i];
  29087. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29088. t[p] = s[p];
  29089. }
  29090. return t;
  29091. };
  29092. var BABYLON;
  29093. (function (BABYLON) {
  29094. var MaterialDefines = /** @class */ (function () {
  29095. function MaterialDefines() {
  29096. this._isDirty = true;
  29097. this._areLightsDirty = true;
  29098. this._areAttributesDirty = true;
  29099. this._areTexturesDirty = true;
  29100. this._areFresnelDirty = true;
  29101. this._areMiscDirty = true;
  29102. this._areImageProcessingDirty = true;
  29103. this._normals = false;
  29104. this._uvs = false;
  29105. this._needNormals = false;
  29106. this._needUVs = false;
  29107. }
  29108. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29109. get: function () {
  29110. return this._isDirty;
  29111. },
  29112. enumerable: true,
  29113. configurable: true
  29114. });
  29115. MaterialDefines.prototype.markAsProcessed = function () {
  29116. this._isDirty = false;
  29117. this._areAttributesDirty = false;
  29118. this._areTexturesDirty = false;
  29119. this._areFresnelDirty = false;
  29120. this._areLightsDirty = false;
  29121. this._areMiscDirty = false;
  29122. this._areImageProcessingDirty = false;
  29123. };
  29124. MaterialDefines.prototype.markAsUnprocessed = function () {
  29125. this._isDirty = true;
  29126. };
  29127. MaterialDefines.prototype.markAllAsDirty = function () {
  29128. this._areTexturesDirty = true;
  29129. this._areAttributesDirty = true;
  29130. this._areLightsDirty = true;
  29131. this._areFresnelDirty = true;
  29132. this._areMiscDirty = true;
  29133. this._areImageProcessingDirty = true;
  29134. this._isDirty = true;
  29135. };
  29136. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29137. this._areImageProcessingDirty = true;
  29138. this._isDirty = true;
  29139. };
  29140. MaterialDefines.prototype.markAsLightDirty = function () {
  29141. this._areLightsDirty = true;
  29142. this._isDirty = true;
  29143. };
  29144. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29145. this._areAttributesDirty = true;
  29146. this._isDirty = true;
  29147. };
  29148. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29149. this._areTexturesDirty = true;
  29150. this._isDirty = true;
  29151. };
  29152. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29153. this._areFresnelDirty = true;
  29154. this._isDirty = true;
  29155. };
  29156. MaterialDefines.prototype.markAsMiscDirty = function () {
  29157. this._areMiscDirty = true;
  29158. this._isDirty = true;
  29159. };
  29160. MaterialDefines.prototype.rebuild = function () {
  29161. if (this._keys) {
  29162. delete this._keys;
  29163. }
  29164. this._keys = [];
  29165. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29166. var key = _a[_i];
  29167. if (key[0] === "_") {
  29168. continue;
  29169. }
  29170. this._keys.push(key);
  29171. }
  29172. };
  29173. MaterialDefines.prototype.isEqual = function (other) {
  29174. if (this._keys.length !== other._keys.length) {
  29175. return false;
  29176. }
  29177. for (var index = 0; index < this._keys.length; index++) {
  29178. var prop = this._keys[index];
  29179. if (this[prop] !== other[prop]) {
  29180. return false;
  29181. }
  29182. }
  29183. return true;
  29184. };
  29185. MaterialDefines.prototype.cloneTo = function (other) {
  29186. if (this._keys.length !== other._keys.length) {
  29187. other._keys = this._keys.slice(0);
  29188. }
  29189. for (var index = 0; index < this._keys.length; index++) {
  29190. var prop = this._keys[index];
  29191. other[prop] = this[prop];
  29192. }
  29193. };
  29194. MaterialDefines.prototype.reset = function () {
  29195. for (var index = 0; index < this._keys.length; index++) {
  29196. var prop = this._keys[index];
  29197. if (typeof (this[prop]) === "number") {
  29198. this[prop] = 0;
  29199. }
  29200. else {
  29201. this[prop] = false;
  29202. }
  29203. }
  29204. };
  29205. MaterialDefines.prototype.toString = function () {
  29206. var result = "";
  29207. for (var index = 0; index < this._keys.length; index++) {
  29208. var prop = this._keys[index];
  29209. var value = this[prop];
  29210. if (typeof (value) === "number") {
  29211. result += "#define " + prop + " " + this[prop] + "\n";
  29212. }
  29213. else if (value) {
  29214. result += "#define " + prop + "\n";
  29215. }
  29216. }
  29217. return result;
  29218. };
  29219. return MaterialDefines;
  29220. }());
  29221. BABYLON.MaterialDefines = MaterialDefines;
  29222. var Material = /** @class */ (function () {
  29223. function Material(name, scene, doNotAdd) {
  29224. this.checkReadyOnEveryCall = false;
  29225. this.checkReadyOnlyOnce = false;
  29226. this.state = "";
  29227. this._alpha = 1.0;
  29228. this._backFaceCulling = true;
  29229. this.doNotSerialize = false;
  29230. this.storeEffectOnSubMeshes = false;
  29231. /**
  29232. * An event triggered when the material is disposed.
  29233. * @type {BABYLON.Observable}
  29234. */
  29235. this.onDisposeObservable = new BABYLON.Observable();
  29236. /**
  29237. * An event triggered when the material is bound.
  29238. * @type {BABYLON.Observable}
  29239. */
  29240. this.onBindObservable = new BABYLON.Observable();
  29241. /**
  29242. * An event triggered when the material is unbound.
  29243. * @type {BABYLON.Observable}
  29244. */
  29245. this.onUnBindObservable = new BABYLON.Observable();
  29246. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29247. this._needDepthPrePass = false;
  29248. this.disableDepthWrite = false;
  29249. this.forceDepthWrite = false;
  29250. this.separateCullingPass = false;
  29251. this._fogEnabled = true;
  29252. this.pointSize = 1.0;
  29253. this.zOffset = 0;
  29254. this._wasPreviouslyReady = false;
  29255. this._fillMode = Material.TriangleFillMode;
  29256. this.name = name;
  29257. this.id = name || BABYLON.Tools.RandomId();
  29258. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29259. if (this._scene.useRightHandedSystem) {
  29260. this.sideOrientation = Material.ClockWiseSideOrientation;
  29261. }
  29262. else {
  29263. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29264. }
  29265. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29266. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29267. if (!doNotAdd) {
  29268. this._scene.materials.push(this);
  29269. }
  29270. }
  29271. Object.defineProperty(Material, "TriangleFillMode", {
  29272. get: function () {
  29273. return Material._TriangleFillMode;
  29274. },
  29275. enumerable: true,
  29276. configurable: true
  29277. });
  29278. Object.defineProperty(Material, "WireFrameFillMode", {
  29279. get: function () {
  29280. return Material._WireFrameFillMode;
  29281. },
  29282. enumerable: true,
  29283. configurable: true
  29284. });
  29285. Object.defineProperty(Material, "PointFillMode", {
  29286. get: function () {
  29287. return Material._PointFillMode;
  29288. },
  29289. enumerable: true,
  29290. configurable: true
  29291. });
  29292. Object.defineProperty(Material, "PointListDrawMode", {
  29293. get: function () {
  29294. return Material._PointListDrawMode;
  29295. },
  29296. enumerable: true,
  29297. configurable: true
  29298. });
  29299. Object.defineProperty(Material, "LineListDrawMode", {
  29300. get: function () {
  29301. return Material._LineListDrawMode;
  29302. },
  29303. enumerable: true,
  29304. configurable: true
  29305. });
  29306. Object.defineProperty(Material, "LineLoopDrawMode", {
  29307. get: function () {
  29308. return Material._LineLoopDrawMode;
  29309. },
  29310. enumerable: true,
  29311. configurable: true
  29312. });
  29313. Object.defineProperty(Material, "LineStripDrawMode", {
  29314. get: function () {
  29315. return Material._LineStripDrawMode;
  29316. },
  29317. enumerable: true,
  29318. configurable: true
  29319. });
  29320. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29321. get: function () {
  29322. return Material._TriangleStripDrawMode;
  29323. },
  29324. enumerable: true,
  29325. configurable: true
  29326. });
  29327. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29328. get: function () {
  29329. return Material._TriangleFanDrawMode;
  29330. },
  29331. enumerable: true,
  29332. configurable: true
  29333. });
  29334. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29335. get: function () {
  29336. return Material._ClockWiseSideOrientation;
  29337. },
  29338. enumerable: true,
  29339. configurable: true
  29340. });
  29341. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29342. get: function () {
  29343. return Material._CounterClockWiseSideOrientation;
  29344. },
  29345. enumerable: true,
  29346. configurable: true
  29347. });
  29348. Object.defineProperty(Material, "TextureDirtyFlag", {
  29349. get: function () {
  29350. return Material._TextureDirtyFlag;
  29351. },
  29352. enumerable: true,
  29353. configurable: true
  29354. });
  29355. Object.defineProperty(Material, "LightDirtyFlag", {
  29356. get: function () {
  29357. return Material._LightDirtyFlag;
  29358. },
  29359. enumerable: true,
  29360. configurable: true
  29361. });
  29362. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29363. get: function () {
  29364. return Material._FresnelDirtyFlag;
  29365. },
  29366. enumerable: true,
  29367. configurable: true
  29368. });
  29369. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29370. get: function () {
  29371. return Material._AttributesDirtyFlag;
  29372. },
  29373. enumerable: true,
  29374. configurable: true
  29375. });
  29376. Object.defineProperty(Material, "MiscDirtyFlag", {
  29377. get: function () {
  29378. return Material._MiscDirtyFlag;
  29379. },
  29380. enumerable: true,
  29381. configurable: true
  29382. });
  29383. Object.defineProperty(Material.prototype, "alpha", {
  29384. get: function () {
  29385. return this._alpha;
  29386. },
  29387. set: function (value) {
  29388. if (this._alpha === value) {
  29389. return;
  29390. }
  29391. this._alpha = value;
  29392. this.markAsDirty(Material.MiscDirtyFlag);
  29393. },
  29394. enumerable: true,
  29395. configurable: true
  29396. });
  29397. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29398. get: function () {
  29399. return this._backFaceCulling;
  29400. },
  29401. set: function (value) {
  29402. if (this._backFaceCulling === value) {
  29403. return;
  29404. }
  29405. this._backFaceCulling = value;
  29406. this.markAsDirty(Material.TextureDirtyFlag);
  29407. },
  29408. enumerable: true,
  29409. configurable: true
  29410. });
  29411. Object.defineProperty(Material.prototype, "onDispose", {
  29412. set: function (callback) {
  29413. if (this._onDisposeObserver) {
  29414. this.onDisposeObservable.remove(this._onDisposeObserver);
  29415. }
  29416. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29417. },
  29418. enumerable: true,
  29419. configurable: true
  29420. });
  29421. Object.defineProperty(Material.prototype, "onBind", {
  29422. set: function (callback) {
  29423. if (this._onBindObserver) {
  29424. this.onBindObservable.remove(this._onBindObserver);
  29425. }
  29426. this._onBindObserver = this.onBindObservable.add(callback);
  29427. },
  29428. enumerable: true,
  29429. configurable: true
  29430. });
  29431. Object.defineProperty(Material.prototype, "alphaMode", {
  29432. get: function () {
  29433. return this._alphaMode;
  29434. },
  29435. set: function (value) {
  29436. if (this._alphaMode === value) {
  29437. return;
  29438. }
  29439. this._alphaMode = value;
  29440. this.markAsDirty(Material.TextureDirtyFlag);
  29441. },
  29442. enumerable: true,
  29443. configurable: true
  29444. });
  29445. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29446. get: function () {
  29447. return this._needDepthPrePass;
  29448. },
  29449. set: function (value) {
  29450. if (this._needDepthPrePass === value) {
  29451. return;
  29452. }
  29453. this._needDepthPrePass = value;
  29454. if (this._needDepthPrePass) {
  29455. this.checkReadyOnEveryCall = true;
  29456. }
  29457. },
  29458. enumerable: true,
  29459. configurable: true
  29460. });
  29461. Object.defineProperty(Material.prototype, "fogEnabled", {
  29462. get: function () {
  29463. return this._fogEnabled;
  29464. },
  29465. set: function (value) {
  29466. if (this._fogEnabled === value) {
  29467. return;
  29468. }
  29469. this._fogEnabled = value;
  29470. this.markAsDirty(Material.MiscDirtyFlag);
  29471. },
  29472. enumerable: true,
  29473. configurable: true
  29474. });
  29475. Object.defineProperty(Material.prototype, "wireframe", {
  29476. get: function () {
  29477. return this._fillMode === Material.WireFrameFillMode;
  29478. },
  29479. set: function (value) {
  29480. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29481. },
  29482. enumerable: true,
  29483. configurable: true
  29484. });
  29485. Object.defineProperty(Material.prototype, "pointsCloud", {
  29486. get: function () {
  29487. return this._fillMode === Material.PointFillMode;
  29488. },
  29489. set: function (value) {
  29490. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29491. },
  29492. enumerable: true,
  29493. configurable: true
  29494. });
  29495. Object.defineProperty(Material.prototype, "fillMode", {
  29496. get: function () {
  29497. return this._fillMode;
  29498. },
  29499. set: function (value) {
  29500. if (this._fillMode === value) {
  29501. return;
  29502. }
  29503. this._fillMode = value;
  29504. this.markAsDirty(Material.MiscDirtyFlag);
  29505. },
  29506. enumerable: true,
  29507. configurable: true
  29508. });
  29509. /**
  29510. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29511. * subclasses should override adding information pertainent to themselves
  29512. */
  29513. Material.prototype.toString = function (fullDetails) {
  29514. var ret = "Name: " + this.name;
  29515. if (fullDetails) {
  29516. }
  29517. return ret;
  29518. };
  29519. /**
  29520. * Child classes can use it to update shaders
  29521. */
  29522. Material.prototype.getClassName = function () {
  29523. return "Material";
  29524. };
  29525. Object.defineProperty(Material.prototype, "isFrozen", {
  29526. get: function () {
  29527. return this.checkReadyOnlyOnce;
  29528. },
  29529. enumerable: true,
  29530. configurable: true
  29531. });
  29532. Material.prototype.freeze = function () {
  29533. this.checkReadyOnlyOnce = true;
  29534. };
  29535. Material.prototype.unfreeze = function () {
  29536. this.checkReadyOnlyOnce = false;
  29537. };
  29538. Material.prototype.isReady = function (mesh, useInstances) {
  29539. return true;
  29540. };
  29541. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29542. return false;
  29543. };
  29544. Material.prototype.getEffect = function () {
  29545. return this._effect;
  29546. };
  29547. Material.prototype.getScene = function () {
  29548. return this._scene;
  29549. };
  29550. Material.prototype.needAlphaBlending = function () {
  29551. return (this.alpha < 1.0);
  29552. };
  29553. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29554. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29555. };
  29556. Material.prototype.needAlphaTesting = function () {
  29557. return false;
  29558. };
  29559. Material.prototype.getAlphaTestTexture = function () {
  29560. return null;
  29561. };
  29562. Material.prototype.markDirty = function () {
  29563. this._wasPreviouslyReady = false;
  29564. };
  29565. Material.prototype._preBind = function (effect, overrideOrientation) {
  29566. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29567. var engine = this._scene.getEngine();
  29568. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29569. var reverse = orientation === Material.ClockWiseSideOrientation;
  29570. engine.enableEffect(effect ? effect : this._effect);
  29571. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29572. return reverse;
  29573. };
  29574. Material.prototype.bind = function (world, mesh) {
  29575. };
  29576. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29577. };
  29578. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29579. };
  29580. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29581. sceneUbo.bindToEffect(effect, "Scene");
  29582. };
  29583. Material.prototype.bindView = function (effect) {
  29584. if (!this._useUBO) {
  29585. effect.setMatrix("view", this.getScene().getViewMatrix());
  29586. }
  29587. else {
  29588. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29589. }
  29590. };
  29591. Material.prototype.bindViewProjection = function (effect) {
  29592. if (!this._useUBO) {
  29593. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29594. }
  29595. else {
  29596. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29597. }
  29598. };
  29599. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29600. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29601. };
  29602. Material.prototype._afterBind = function (mesh) {
  29603. this._scene._cachedMaterial = this;
  29604. if (mesh) {
  29605. this._scene._cachedVisibility = mesh.visibility;
  29606. }
  29607. else {
  29608. this._scene._cachedVisibility = 1;
  29609. }
  29610. if (mesh) {
  29611. this.onBindObservable.notifyObservers(mesh);
  29612. }
  29613. if (this.disableDepthWrite) {
  29614. var engine = this._scene.getEngine();
  29615. this._cachedDepthWriteState = engine.getDepthWrite();
  29616. engine.setDepthWrite(false);
  29617. }
  29618. };
  29619. Material.prototype.unbind = function () {
  29620. this.onUnBindObservable.notifyObservers(this);
  29621. if (this.disableDepthWrite) {
  29622. var engine = this._scene.getEngine();
  29623. engine.setDepthWrite(this._cachedDepthWriteState);
  29624. }
  29625. };
  29626. Material.prototype.getActiveTextures = function () {
  29627. return [];
  29628. };
  29629. Material.prototype.hasTexture = function (texture) {
  29630. return false;
  29631. };
  29632. Material.prototype.clone = function (name) {
  29633. return null;
  29634. };
  29635. Material.prototype.getBindedMeshes = function () {
  29636. var result = new Array();
  29637. for (var index = 0; index < this._scene.meshes.length; index++) {
  29638. var mesh = this._scene.meshes[index];
  29639. if (mesh.material === this) {
  29640. result.push(mesh);
  29641. }
  29642. }
  29643. return result;
  29644. };
  29645. /**
  29646. * Force shader compilation including textures ready check
  29647. */
  29648. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29649. var _this = this;
  29650. var localOptions = __assign({ clipPlane: false }, options);
  29651. var subMesh = new BABYLON.BaseSubMesh();
  29652. var scene = this.getScene();
  29653. var checkReady = function () {
  29654. if (!_this._scene || !_this._scene.getEngine()) {
  29655. return;
  29656. }
  29657. if (subMesh._materialDefines) {
  29658. subMesh._materialDefines._renderId = -1;
  29659. }
  29660. var clipPlaneState = scene.clipPlane;
  29661. if (localOptions.clipPlane) {
  29662. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29663. }
  29664. if (_this.storeEffectOnSubMeshes) {
  29665. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29666. if (onCompiled) {
  29667. onCompiled(_this);
  29668. }
  29669. }
  29670. else {
  29671. setTimeout(checkReady, 16);
  29672. }
  29673. }
  29674. else {
  29675. if (_this.isReady(mesh)) {
  29676. if (onCompiled) {
  29677. onCompiled(_this);
  29678. }
  29679. }
  29680. else {
  29681. setTimeout(checkReady, 16);
  29682. }
  29683. }
  29684. if (options && options.clipPlane) {
  29685. scene.clipPlane = clipPlaneState;
  29686. }
  29687. };
  29688. checkReady();
  29689. };
  29690. Material.prototype.markAsDirty = function (flag) {
  29691. if (flag & Material.TextureDirtyFlag) {
  29692. this._markAllSubMeshesAsTexturesDirty();
  29693. }
  29694. if (flag & Material.LightDirtyFlag) {
  29695. this._markAllSubMeshesAsLightsDirty();
  29696. }
  29697. if (flag & Material.FresnelDirtyFlag) {
  29698. this._markAllSubMeshesAsFresnelDirty();
  29699. }
  29700. if (flag & Material.AttributesDirtyFlag) {
  29701. this._markAllSubMeshesAsAttributesDirty();
  29702. }
  29703. if (flag & Material.MiscDirtyFlag) {
  29704. this._markAllSubMeshesAsMiscDirty();
  29705. }
  29706. this.getScene().resetCachedMaterial();
  29707. };
  29708. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29709. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29710. var mesh = _a[_i];
  29711. if (!mesh.subMeshes) {
  29712. continue;
  29713. }
  29714. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29715. var subMesh = _c[_b];
  29716. if (subMesh.getMaterial() !== this) {
  29717. continue;
  29718. }
  29719. if (!subMesh._materialDefines) {
  29720. continue;
  29721. }
  29722. func(subMesh._materialDefines);
  29723. }
  29724. }
  29725. };
  29726. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29727. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29728. };
  29729. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29730. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29731. };
  29732. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29733. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29734. };
  29735. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29736. this._markAllSubMeshesAsDirty(function (defines) {
  29737. defines.markAsFresnelDirty();
  29738. defines.markAsMiscDirty();
  29739. });
  29740. };
  29741. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29742. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29743. };
  29744. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29745. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29746. };
  29747. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29748. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29749. };
  29750. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29751. this._markAllSubMeshesAsDirty(function (defines) {
  29752. defines.markAsTexturesDirty();
  29753. defines.markAsMiscDirty();
  29754. });
  29755. };
  29756. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29757. // Animations
  29758. this.getScene().stopAnimation(this);
  29759. // Remove from scene
  29760. var index = this._scene.materials.indexOf(this);
  29761. if (index >= 0) {
  29762. this._scene.materials.splice(index, 1);
  29763. }
  29764. // Remove from meshes
  29765. for (index = 0; index < this._scene.meshes.length; index++) {
  29766. var mesh = this._scene.meshes[index];
  29767. if (mesh.material === this) {
  29768. mesh.material = null;
  29769. if (mesh.geometry) {
  29770. var geometry = (mesh.geometry);
  29771. if (this.storeEffectOnSubMeshes) {
  29772. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29773. var subMesh = _a[_i];
  29774. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29775. if (forceDisposeEffect && subMesh._materialEffect) {
  29776. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29777. }
  29778. }
  29779. }
  29780. else {
  29781. geometry._releaseVertexArrayObject(this._effect);
  29782. }
  29783. }
  29784. }
  29785. }
  29786. this._uniformBuffer.dispose();
  29787. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29788. if (forceDisposeEffect && this._effect) {
  29789. if (!this.storeEffectOnSubMeshes) {
  29790. this._scene.getEngine()._releaseEffect(this._effect);
  29791. }
  29792. this._effect = null;
  29793. }
  29794. // Callback
  29795. this.onDisposeObservable.notifyObservers(this);
  29796. this.onDisposeObservable.clear();
  29797. this.onBindObservable.clear();
  29798. this.onUnBindObservable.clear();
  29799. };
  29800. Material.prototype.serialize = function () {
  29801. return BABYLON.SerializationHelper.Serialize(this);
  29802. };
  29803. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29804. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29805. multiMaterial.id = parsedMultiMaterial.id;
  29806. if (BABYLON.Tags) {
  29807. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29808. }
  29809. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29810. var subMatId = parsedMultiMaterial.materials[matIndex];
  29811. if (subMatId) {
  29812. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29813. }
  29814. else {
  29815. multiMaterial.subMaterials.push(null);
  29816. }
  29817. }
  29818. return multiMaterial;
  29819. };
  29820. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29821. if (!parsedMaterial.customType) {
  29822. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29823. }
  29824. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29825. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29826. if (!BABYLON.LegacyPBRMaterial) {
  29827. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29828. return;
  29829. }
  29830. }
  29831. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29832. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29833. ;
  29834. };
  29835. // Triangle views
  29836. Material._TriangleFillMode = 0;
  29837. Material._WireFrameFillMode = 1;
  29838. Material._PointFillMode = 2;
  29839. // Draw modes
  29840. Material._PointListDrawMode = 3;
  29841. Material._LineListDrawMode = 4;
  29842. Material._LineLoopDrawMode = 5;
  29843. Material._LineStripDrawMode = 6;
  29844. Material._TriangleStripDrawMode = 7;
  29845. Material._TriangleFanDrawMode = 8;
  29846. Material._ClockWiseSideOrientation = 0;
  29847. Material._CounterClockWiseSideOrientation = 1;
  29848. Material._TextureDirtyFlag = 1;
  29849. Material._LightDirtyFlag = 2;
  29850. Material._FresnelDirtyFlag = 4;
  29851. Material._AttributesDirtyFlag = 8;
  29852. Material._MiscDirtyFlag = 16;
  29853. __decorate([
  29854. BABYLON.serialize()
  29855. ], Material.prototype, "id", void 0);
  29856. __decorate([
  29857. BABYLON.serialize()
  29858. ], Material.prototype, "name", void 0);
  29859. __decorate([
  29860. BABYLON.serialize()
  29861. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29862. __decorate([
  29863. BABYLON.serialize()
  29864. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29865. __decorate([
  29866. BABYLON.serialize()
  29867. ], Material.prototype, "state", void 0);
  29868. __decorate([
  29869. BABYLON.serialize("alpha")
  29870. ], Material.prototype, "_alpha", void 0);
  29871. __decorate([
  29872. BABYLON.serialize("backFaceCulling")
  29873. ], Material.prototype, "_backFaceCulling", void 0);
  29874. __decorate([
  29875. BABYLON.serialize()
  29876. ], Material.prototype, "sideOrientation", void 0);
  29877. __decorate([
  29878. BABYLON.serialize("alphaMode")
  29879. ], Material.prototype, "_alphaMode", void 0);
  29880. __decorate([
  29881. BABYLON.serialize()
  29882. ], Material.prototype, "_needDepthPrePass", void 0);
  29883. __decorate([
  29884. BABYLON.serialize()
  29885. ], Material.prototype, "disableDepthWrite", void 0);
  29886. __decorate([
  29887. BABYLON.serialize()
  29888. ], Material.prototype, "forceDepthWrite", void 0);
  29889. __decorate([
  29890. BABYLON.serialize()
  29891. ], Material.prototype, "separateCullingPass", void 0);
  29892. __decorate([
  29893. BABYLON.serialize("fogEnabled")
  29894. ], Material.prototype, "_fogEnabled", void 0);
  29895. __decorate([
  29896. BABYLON.serialize()
  29897. ], Material.prototype, "pointSize", void 0);
  29898. __decorate([
  29899. BABYLON.serialize()
  29900. ], Material.prototype, "zOffset", void 0);
  29901. __decorate([
  29902. BABYLON.serialize()
  29903. ], Material.prototype, "wireframe", null);
  29904. __decorate([
  29905. BABYLON.serialize()
  29906. ], Material.prototype, "pointsCloud", null);
  29907. __decorate([
  29908. BABYLON.serialize()
  29909. ], Material.prototype, "fillMode", null);
  29910. return Material;
  29911. }());
  29912. BABYLON.Material = Material;
  29913. })(BABYLON || (BABYLON = {}));
  29914. //# sourceMappingURL=babylon.material.js.map
  29915. var BABYLON;
  29916. (function (BABYLON) {
  29917. var UniformBuffer = /** @class */ (function () {
  29918. /**
  29919. * Uniform buffer objects.
  29920. *
  29921. * Handles blocks of uniform on the GPU.
  29922. *
  29923. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29924. *
  29925. * For more information, please refer to :
  29926. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29927. */
  29928. function UniformBuffer(engine, data, dynamic) {
  29929. this._engine = engine;
  29930. this._noUBO = !engine.supportsUniformBuffers;
  29931. this._dynamic = dynamic;
  29932. this._data = data || [];
  29933. this._uniformLocations = {};
  29934. this._uniformSizes = {};
  29935. this._uniformLocationPointer = 0;
  29936. this._needSync = false;
  29937. if (this._noUBO) {
  29938. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29939. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29940. this.updateFloat = this._updateFloatForEffect;
  29941. this.updateFloat2 = this._updateFloat2ForEffect;
  29942. this.updateFloat3 = this._updateFloat3ForEffect;
  29943. this.updateFloat4 = this._updateFloat4ForEffect;
  29944. this.updateMatrix = this._updateMatrixForEffect;
  29945. this.updateVector3 = this._updateVector3ForEffect;
  29946. this.updateVector4 = this._updateVector4ForEffect;
  29947. this.updateColor3 = this._updateColor3ForEffect;
  29948. this.updateColor4 = this._updateColor4ForEffect;
  29949. }
  29950. else {
  29951. this._engine._uniformBuffers.push(this);
  29952. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29953. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29954. this.updateFloat = this._updateFloatForUniform;
  29955. this.updateFloat2 = this._updateFloat2ForUniform;
  29956. this.updateFloat3 = this._updateFloat3ForUniform;
  29957. this.updateFloat4 = this._updateFloat4ForUniform;
  29958. this.updateMatrix = this._updateMatrixForUniform;
  29959. this.updateVector3 = this._updateVector3ForUniform;
  29960. this.updateVector4 = this._updateVector4ForUniform;
  29961. this.updateColor3 = this._updateColor3ForUniform;
  29962. this.updateColor4 = this._updateColor4ForUniform;
  29963. }
  29964. }
  29965. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29966. // Properties
  29967. /**
  29968. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29969. * or just falling back on setUniformXXX calls.
  29970. */
  29971. get: function () {
  29972. return !this._noUBO;
  29973. },
  29974. enumerable: true,
  29975. configurable: true
  29976. });
  29977. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29978. /**
  29979. * Indicates if the WebGL underlying uniform buffer is in sync
  29980. * with the javascript cache data.
  29981. */
  29982. get: function () {
  29983. return !this._needSync;
  29984. },
  29985. enumerable: true,
  29986. configurable: true
  29987. });
  29988. /**
  29989. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29990. * Also, a dynamic UniformBuffer will disable cache verification and always
  29991. * update the underlying WebGL uniform buffer to the GPU.
  29992. */
  29993. UniformBuffer.prototype.isDynamic = function () {
  29994. return this._dynamic !== undefined;
  29995. };
  29996. /**
  29997. * The data cache on JS side.
  29998. */
  29999. UniformBuffer.prototype.getData = function () {
  30000. return this._bufferData;
  30001. };
  30002. /**
  30003. * The underlying WebGL Uniform buffer.
  30004. */
  30005. UniformBuffer.prototype.getBuffer = function () {
  30006. return this._buffer;
  30007. };
  30008. /**
  30009. * std140 layout specifies how to align data within an UBO structure.
  30010. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  30011. * for specs.
  30012. */
  30013. UniformBuffer.prototype._fillAlignment = function (size) {
  30014. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  30015. // and 4x4 matrices
  30016. // TODO : change if other types are used
  30017. var alignment;
  30018. if (size <= 2) {
  30019. alignment = size;
  30020. }
  30021. else {
  30022. alignment = 4;
  30023. }
  30024. if ((this._uniformLocationPointer % alignment) !== 0) {
  30025. var oldPointer = this._uniformLocationPointer;
  30026. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  30027. var diff = this._uniformLocationPointer - oldPointer;
  30028. for (var i = 0; i < diff; i++) {
  30029. this._data.push(0);
  30030. }
  30031. }
  30032. };
  30033. /**
  30034. * Adds an uniform in the buffer.
  30035. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  30036. * for the layout to be correct !
  30037. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30038. * @param {number|number[]} size Data size, or data directly.
  30039. */
  30040. UniformBuffer.prototype.addUniform = function (name, size) {
  30041. if (this._noUBO) {
  30042. return;
  30043. }
  30044. if (this._uniformLocations[name] !== undefined) {
  30045. // Already existing uniform
  30046. return;
  30047. }
  30048. // This function must be called in the order of the shader layout !
  30049. // size can be the size of the uniform, or data directly
  30050. var data;
  30051. if (size instanceof Array) {
  30052. data = size;
  30053. size = data.length;
  30054. }
  30055. else {
  30056. size = size;
  30057. data = [];
  30058. // Fill with zeros
  30059. for (var i = 0; i < size; i++) {
  30060. data.push(0);
  30061. }
  30062. }
  30063. this._fillAlignment(size);
  30064. this._uniformSizes[name] = size;
  30065. this._uniformLocations[name] = this._uniformLocationPointer;
  30066. this._uniformLocationPointer += size;
  30067. for (var i = 0; i < size; i++) {
  30068. this._data.push(data[i]);
  30069. }
  30070. this._needSync = true;
  30071. };
  30072. /**
  30073. * Wrapper for addUniform.
  30074. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30075. * @param {Matrix} mat A 4x4 matrix.
  30076. */
  30077. UniformBuffer.prototype.addMatrix = function (name, mat) {
  30078. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  30079. };
  30080. /**
  30081. * Wrapper for addUniform.
  30082. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30083. * @param {number} x
  30084. * @param {number} y
  30085. */
  30086. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  30087. var temp = [x, y];
  30088. this.addUniform(name, temp);
  30089. };
  30090. /**
  30091. * Wrapper for addUniform.
  30092. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30093. * @param {number} x
  30094. * @param {number} y
  30095. * @param {number} z
  30096. */
  30097. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  30098. var temp = [x, y, z];
  30099. this.addUniform(name, temp);
  30100. };
  30101. /**
  30102. * Wrapper for addUniform.
  30103. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30104. * @param {Color3} color
  30105. */
  30106. UniformBuffer.prototype.addColor3 = function (name, color) {
  30107. var temp = new Array();
  30108. color.toArray(temp);
  30109. this.addUniform(name, temp);
  30110. };
  30111. /**
  30112. * Wrapper for addUniform.
  30113. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30114. * @param {Color3} color
  30115. * @param {number} alpha
  30116. */
  30117. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  30118. var temp = new Array();
  30119. color.toArray(temp);
  30120. temp.push(alpha);
  30121. this.addUniform(name, temp);
  30122. };
  30123. /**
  30124. * Wrapper for addUniform.
  30125. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30126. * @param {Vector3} vector
  30127. */
  30128. UniformBuffer.prototype.addVector3 = function (name, vector) {
  30129. var temp = new Array();
  30130. vector.toArray(temp);
  30131. this.addUniform(name, temp);
  30132. };
  30133. /**
  30134. * Wrapper for addUniform.
  30135. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30136. */
  30137. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  30138. this.addUniform(name, 12);
  30139. };
  30140. /**
  30141. * Wrapper for addUniform.
  30142. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30143. */
  30144. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30145. this.addUniform(name, 8);
  30146. };
  30147. /**
  30148. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30149. */
  30150. UniformBuffer.prototype.create = function () {
  30151. if (this._noUBO) {
  30152. return;
  30153. }
  30154. if (this._buffer) {
  30155. return; // nothing to do
  30156. }
  30157. // See spec, alignment must be filled as a vec4
  30158. this._fillAlignment(4);
  30159. this._bufferData = new Float32Array(this._data);
  30160. this._rebuild();
  30161. this._needSync = true;
  30162. };
  30163. UniformBuffer.prototype._rebuild = function () {
  30164. if (this._noUBO) {
  30165. return;
  30166. }
  30167. if (this._dynamic) {
  30168. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30169. }
  30170. else {
  30171. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30172. }
  30173. };
  30174. /**
  30175. * Updates the WebGL Uniform Buffer on the GPU.
  30176. * If the `dynamic` flag is set to true, no cache comparison is done.
  30177. * Otherwise, the buffer will be updated only if the cache differs.
  30178. */
  30179. UniformBuffer.prototype.update = function () {
  30180. if (!this._buffer) {
  30181. this.create();
  30182. return;
  30183. }
  30184. if (!this._dynamic && !this._needSync) {
  30185. return;
  30186. }
  30187. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30188. this._needSync = false;
  30189. };
  30190. /**
  30191. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30192. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30193. * @param {number[]|Float32Array} data Flattened data
  30194. * @param {number} size Size of the data.
  30195. */
  30196. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30197. var location = this._uniformLocations[uniformName];
  30198. if (location === undefined) {
  30199. if (this._buffer) {
  30200. // Cannot add an uniform if the buffer is already created
  30201. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30202. return;
  30203. }
  30204. this.addUniform(uniformName, size);
  30205. location = this._uniformLocations[uniformName];
  30206. }
  30207. if (!this._buffer) {
  30208. this.create();
  30209. }
  30210. if (!this._dynamic) {
  30211. // Cache for static uniform buffers
  30212. var changed = false;
  30213. for (var i = 0; i < size; i++) {
  30214. if (this._bufferData[location + i] !== data[i]) {
  30215. changed = true;
  30216. this._bufferData[location + i] = data[i];
  30217. }
  30218. }
  30219. this._needSync = this._needSync || changed;
  30220. }
  30221. else {
  30222. // No cache for dynamic
  30223. for (var i = 0; i < size; i++) {
  30224. this._bufferData[location + i] = data[i];
  30225. }
  30226. }
  30227. };
  30228. // Update methods
  30229. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30230. // To match std140, matrix must be realigned
  30231. for (var i = 0; i < 3; i++) {
  30232. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30233. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30234. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30235. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30236. }
  30237. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30238. };
  30239. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30240. this._currentEffect.setMatrix3x3(name, matrix);
  30241. };
  30242. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30243. this._currentEffect.setMatrix2x2(name, matrix);
  30244. };
  30245. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30246. // To match std140, matrix must be realigned
  30247. for (var i = 0; i < 2; i++) {
  30248. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30249. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30250. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30251. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30252. }
  30253. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30254. };
  30255. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30256. this._currentEffect.setFloat(name, x);
  30257. };
  30258. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30259. UniformBuffer._tempBuffer[0] = x;
  30260. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30261. };
  30262. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30263. if (suffix === void 0) { suffix = ""; }
  30264. this._currentEffect.setFloat2(name + suffix, x, y);
  30265. };
  30266. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30267. if (suffix === void 0) { suffix = ""; }
  30268. UniformBuffer._tempBuffer[0] = x;
  30269. UniformBuffer._tempBuffer[1] = y;
  30270. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30271. };
  30272. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30273. if (suffix === void 0) { suffix = ""; }
  30274. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30275. };
  30276. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30277. if (suffix === void 0) { suffix = ""; }
  30278. UniformBuffer._tempBuffer[0] = x;
  30279. UniformBuffer._tempBuffer[1] = y;
  30280. UniformBuffer._tempBuffer[2] = z;
  30281. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30282. };
  30283. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30284. if (suffix === void 0) { suffix = ""; }
  30285. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30286. };
  30287. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30288. if (suffix === void 0) { suffix = ""; }
  30289. UniformBuffer._tempBuffer[0] = x;
  30290. UniformBuffer._tempBuffer[1] = y;
  30291. UniformBuffer._tempBuffer[2] = z;
  30292. UniformBuffer._tempBuffer[3] = w;
  30293. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30294. };
  30295. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30296. this._currentEffect.setMatrix(name, mat);
  30297. };
  30298. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30299. this.updateUniform(name, mat.toArray(), 16);
  30300. };
  30301. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30302. this._currentEffect.setVector3(name, vector);
  30303. };
  30304. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30305. vector.toArray(UniformBuffer._tempBuffer);
  30306. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30307. };
  30308. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30309. this._currentEffect.setVector4(name, vector);
  30310. };
  30311. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30312. vector.toArray(UniformBuffer._tempBuffer);
  30313. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30314. };
  30315. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30316. if (suffix === void 0) { suffix = ""; }
  30317. this._currentEffect.setColor3(name + suffix, color);
  30318. };
  30319. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30320. if (suffix === void 0) { suffix = ""; }
  30321. color.toArray(UniformBuffer._tempBuffer);
  30322. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30323. };
  30324. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30325. if (suffix === void 0) { suffix = ""; }
  30326. this._currentEffect.setColor4(name + suffix, color, alpha);
  30327. };
  30328. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30329. if (suffix === void 0) { suffix = ""; }
  30330. color.toArray(UniformBuffer._tempBuffer);
  30331. UniformBuffer._tempBuffer[3] = alpha;
  30332. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30333. };
  30334. /**
  30335. * Sets a sampler uniform on the effect.
  30336. * @param {string} name Name of the sampler.
  30337. * @param {Texture} texture
  30338. */
  30339. UniformBuffer.prototype.setTexture = function (name, texture) {
  30340. this._currentEffect.setTexture(name, texture);
  30341. };
  30342. /**
  30343. * Directly updates the value of the uniform in the cache AND on the GPU.
  30344. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30345. * @param {number[]|Float32Array} data Flattened data
  30346. */
  30347. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30348. this.updateUniform(uniformName, data, data.length);
  30349. this.update();
  30350. };
  30351. /**
  30352. * Binds this uniform buffer to an effect.
  30353. * @param {Effect} effect
  30354. * @param {string} name Name of the uniform block in the shader.
  30355. */
  30356. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30357. this._currentEffect = effect;
  30358. if (this._noUBO || !this._buffer) {
  30359. return;
  30360. }
  30361. effect.bindUniformBuffer(this._buffer, name);
  30362. };
  30363. /**
  30364. * Disposes the uniform buffer.
  30365. */
  30366. UniformBuffer.prototype.dispose = function () {
  30367. if (this._noUBO) {
  30368. return;
  30369. }
  30370. var index = this._engine._uniformBuffers.indexOf(this);
  30371. if (index !== -1) {
  30372. this._engine._uniformBuffers.splice(index, 1);
  30373. }
  30374. if (!this._buffer) {
  30375. return;
  30376. }
  30377. if (this._engine._releaseBuffer(this._buffer)) {
  30378. this._buffer = null;
  30379. }
  30380. };
  30381. // Pool for avoiding memory leaks
  30382. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30383. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30384. return UniformBuffer;
  30385. }());
  30386. BABYLON.UniformBuffer = UniformBuffer;
  30387. })(BABYLON || (BABYLON = {}));
  30388. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30389. var BABYLON;
  30390. (function (BABYLON) {
  30391. var VertexData = /** @class */ (function () {
  30392. function VertexData() {
  30393. }
  30394. VertexData.prototype.set = function (data, kind) {
  30395. switch (kind) {
  30396. case BABYLON.VertexBuffer.PositionKind:
  30397. this.positions = data;
  30398. break;
  30399. case BABYLON.VertexBuffer.NormalKind:
  30400. this.normals = data;
  30401. break;
  30402. case BABYLON.VertexBuffer.TangentKind:
  30403. this.tangents = data;
  30404. break;
  30405. case BABYLON.VertexBuffer.UVKind:
  30406. this.uvs = data;
  30407. break;
  30408. case BABYLON.VertexBuffer.UV2Kind:
  30409. this.uvs2 = data;
  30410. break;
  30411. case BABYLON.VertexBuffer.UV3Kind:
  30412. this.uvs3 = data;
  30413. break;
  30414. case BABYLON.VertexBuffer.UV4Kind:
  30415. this.uvs4 = data;
  30416. break;
  30417. case BABYLON.VertexBuffer.UV5Kind:
  30418. this.uvs5 = data;
  30419. break;
  30420. case BABYLON.VertexBuffer.UV6Kind:
  30421. this.uvs6 = data;
  30422. break;
  30423. case BABYLON.VertexBuffer.ColorKind:
  30424. this.colors = data;
  30425. break;
  30426. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30427. this.matricesIndices = data;
  30428. break;
  30429. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30430. this.matricesWeights = data;
  30431. break;
  30432. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30433. this.matricesIndicesExtra = data;
  30434. break;
  30435. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30436. this.matricesWeightsExtra = data;
  30437. break;
  30438. }
  30439. };
  30440. /**
  30441. * Associates the vertexData to the passed Mesh.
  30442. * Sets it as updatable or not (default `false`).
  30443. * Returns the VertexData.
  30444. */
  30445. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30446. this._applyTo(mesh, updatable);
  30447. return this;
  30448. };
  30449. /**
  30450. * Associates the vertexData to the passed Geometry.
  30451. * Sets it as updatable or not (default `false`).
  30452. * Returns the VertexData.
  30453. */
  30454. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30455. this._applyTo(geometry, updatable);
  30456. return this;
  30457. };
  30458. /**
  30459. * Updates the associated mesh.
  30460. * Returns the VertexData.
  30461. */
  30462. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30463. this._update(mesh);
  30464. return this;
  30465. };
  30466. /**
  30467. * Updates the associated geometry.
  30468. * Returns the VertexData.
  30469. */
  30470. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30471. this._update(geometry);
  30472. return this;
  30473. };
  30474. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30475. if (updatable === void 0) { updatable = false; }
  30476. if (this.positions) {
  30477. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30478. }
  30479. if (this.normals) {
  30480. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30481. }
  30482. if (this.tangents) {
  30483. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30484. }
  30485. if (this.uvs) {
  30486. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30487. }
  30488. if (this.uvs2) {
  30489. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30490. }
  30491. if (this.uvs3) {
  30492. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30493. }
  30494. if (this.uvs4) {
  30495. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30496. }
  30497. if (this.uvs5) {
  30498. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30499. }
  30500. if (this.uvs6) {
  30501. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30502. }
  30503. if (this.colors) {
  30504. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30505. }
  30506. if (this.matricesIndices) {
  30507. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30508. }
  30509. if (this.matricesWeights) {
  30510. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30511. }
  30512. if (this.matricesIndicesExtra) {
  30513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30514. }
  30515. if (this.matricesWeightsExtra) {
  30516. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30517. }
  30518. if (this.indices) {
  30519. meshOrGeometry.setIndices(this.indices, null, updatable);
  30520. }
  30521. return this;
  30522. };
  30523. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30524. if (this.positions) {
  30525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30526. }
  30527. if (this.normals) {
  30528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30529. }
  30530. if (this.tangents) {
  30531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30532. }
  30533. if (this.uvs) {
  30534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30535. }
  30536. if (this.uvs2) {
  30537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30538. }
  30539. if (this.uvs3) {
  30540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30541. }
  30542. if (this.uvs4) {
  30543. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30544. }
  30545. if (this.uvs5) {
  30546. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30547. }
  30548. if (this.uvs6) {
  30549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30550. }
  30551. if (this.colors) {
  30552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30553. }
  30554. if (this.matricesIndices) {
  30555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30556. }
  30557. if (this.matricesWeights) {
  30558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30559. }
  30560. if (this.matricesIndicesExtra) {
  30561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30562. }
  30563. if (this.matricesWeightsExtra) {
  30564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30565. }
  30566. if (this.indices) {
  30567. meshOrGeometry.setIndices(this.indices, null);
  30568. }
  30569. return this;
  30570. };
  30571. /**
  30572. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30573. * Returns the VertexData.
  30574. */
  30575. VertexData.prototype.transform = function (matrix) {
  30576. var transformed = BABYLON.Vector3.Zero();
  30577. var index;
  30578. if (this.positions) {
  30579. var position = BABYLON.Vector3.Zero();
  30580. for (index = 0; index < this.positions.length; index += 3) {
  30581. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30582. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30583. this.positions[index] = transformed.x;
  30584. this.positions[index + 1] = transformed.y;
  30585. this.positions[index + 2] = transformed.z;
  30586. }
  30587. }
  30588. if (this.normals) {
  30589. var normal = BABYLON.Vector3.Zero();
  30590. for (index = 0; index < this.normals.length; index += 3) {
  30591. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30592. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30593. this.normals[index] = transformed.x;
  30594. this.normals[index + 1] = transformed.y;
  30595. this.normals[index + 2] = transformed.z;
  30596. }
  30597. }
  30598. if (this.tangents) {
  30599. var tangent = BABYLON.Vector4.Zero();
  30600. var tangentTransformed = BABYLON.Vector4.Zero();
  30601. for (index = 0; index < this.tangents.length; index += 4) {
  30602. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30603. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30604. this.tangents[index] = tangentTransformed.x;
  30605. this.tangents[index + 1] = tangentTransformed.y;
  30606. this.tangents[index + 2] = tangentTransformed.z;
  30607. this.tangents[index + 3] = tangentTransformed.w;
  30608. }
  30609. }
  30610. return this;
  30611. };
  30612. /**
  30613. * Merges the passed VertexData into the current one.
  30614. * Returns the modified VertexData.
  30615. */
  30616. VertexData.prototype.merge = function (other, options) {
  30617. options = options || {};
  30618. if (other.indices) {
  30619. if (!this.indices) {
  30620. this.indices = [];
  30621. }
  30622. var offset = this.positions ? this.positions.length / 3 : 0;
  30623. for (var index = 0; index < other.indices.length; index++) {
  30624. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30625. this.indices.push(other.indices[index] + offset);
  30626. }
  30627. }
  30628. this.positions = this._mergeElement(this.positions, other.positions);
  30629. if (!this.positions) {
  30630. return this;
  30631. }
  30632. var count = this.positions.length / 3;
  30633. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30634. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30635. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30636. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30637. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30638. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30639. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30640. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30641. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30642. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30643. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30644. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30645. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30646. return this;
  30647. };
  30648. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30649. if (length === void 0) { length = 0; }
  30650. if (defaultValue === void 0) { defaultValue = 0; }
  30651. if (!other && !source) {
  30652. return null;
  30653. }
  30654. if (!other) {
  30655. var padding = new Float32Array(source.length);
  30656. padding.fill(defaultValue);
  30657. return this._mergeElement(source, padding, length);
  30658. }
  30659. if (!source) {
  30660. if (length === 0 || length === other.length) {
  30661. return other;
  30662. }
  30663. var padding = new Float32Array(length - other.length);
  30664. padding.fill(defaultValue);
  30665. return this._mergeElement(padding, other, length);
  30666. }
  30667. var len = other.length + source.length;
  30668. var isSrcTypedArray = source instanceof Float32Array;
  30669. var isOthTypedArray = other instanceof Float32Array;
  30670. // use non-loop method when the source is Float32Array
  30671. if (isSrcTypedArray) {
  30672. var ret32 = new Float32Array(len);
  30673. ret32.set(source);
  30674. ret32.set(other, source.length);
  30675. return ret32;
  30676. // source is number[], when other is also use concat
  30677. }
  30678. else if (!isOthTypedArray) {
  30679. return source.concat(other);
  30680. // source is a number[], but other is a Float32Array, loop required
  30681. }
  30682. else {
  30683. var ret = source.slice(0); // copy source to a separate array
  30684. for (var i = 0, len = other.length; i < len; i++) {
  30685. ret.push(other[i]);
  30686. }
  30687. return ret;
  30688. }
  30689. };
  30690. /**
  30691. * Serializes the VertexData.
  30692. * Returns a serialized object.
  30693. */
  30694. VertexData.prototype.serialize = function () {
  30695. var serializationObject = this.serialize();
  30696. if (this.positions) {
  30697. serializationObject.positions = this.positions;
  30698. }
  30699. if (this.normals) {
  30700. serializationObject.normals = this.normals;
  30701. }
  30702. if (this.tangents) {
  30703. serializationObject.tangents = this.tangents;
  30704. }
  30705. if (this.uvs) {
  30706. serializationObject.uvs = this.uvs;
  30707. }
  30708. if (this.uvs2) {
  30709. serializationObject.uvs2 = this.uvs2;
  30710. }
  30711. if (this.uvs3) {
  30712. serializationObject.uvs3 = this.uvs3;
  30713. }
  30714. if (this.uvs4) {
  30715. serializationObject.uvs4 = this.uvs4;
  30716. }
  30717. if (this.uvs5) {
  30718. serializationObject.uvs5 = this.uvs5;
  30719. }
  30720. if (this.uvs6) {
  30721. serializationObject.uvs6 = this.uvs6;
  30722. }
  30723. if (this.colors) {
  30724. serializationObject.colors = this.colors;
  30725. }
  30726. if (this.matricesIndices) {
  30727. serializationObject.matricesIndices = this.matricesIndices;
  30728. serializationObject.matricesIndices._isExpanded = true;
  30729. }
  30730. if (this.matricesWeights) {
  30731. serializationObject.matricesWeights = this.matricesWeights;
  30732. }
  30733. if (this.matricesIndicesExtra) {
  30734. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30735. serializationObject.matricesIndicesExtra._isExpanded = true;
  30736. }
  30737. if (this.matricesWeightsExtra) {
  30738. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30739. }
  30740. serializationObject.indices = this.indices;
  30741. return serializationObject;
  30742. };
  30743. // Statics
  30744. /**
  30745. * Returns the object VertexData associated to the passed mesh.
  30746. */
  30747. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30748. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30749. };
  30750. /**
  30751. * Returns the object VertexData associated to the passed geometry.
  30752. */
  30753. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30754. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30755. };
  30756. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30757. var result = new VertexData();
  30758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30759. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30760. }
  30761. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30762. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30763. }
  30764. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30765. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30766. }
  30767. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30768. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30769. }
  30770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30771. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30772. }
  30773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30774. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30775. }
  30776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30777. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30778. }
  30779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30780. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30781. }
  30782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30783. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30784. }
  30785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30786. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30787. }
  30788. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30789. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30790. }
  30791. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30792. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30793. }
  30794. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30795. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30796. }
  30797. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30798. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30799. }
  30800. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30801. return result;
  30802. };
  30803. /**
  30804. * Creates the vertexData of the Ribbon.
  30805. */
  30806. VertexData.CreateRibbon = function (options) {
  30807. var pathArray = options.pathArray;
  30808. var closeArray = options.closeArray || false;
  30809. var closePath = options.closePath || false;
  30810. var invertUV = options.invertUV || false;
  30811. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30812. var offset = options.offset || defaultOffset;
  30813. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30814. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30815. var customUV = options.uvs;
  30816. var customColors = options.colors;
  30817. var positions = [];
  30818. var indices = [];
  30819. var normals = [];
  30820. var uvs = [];
  30821. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30822. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30823. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30824. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30825. var minlg; // minimal length among all paths from pathArray
  30826. var lg = []; // array of path lengths : nb of vertex per path
  30827. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30828. var p; // path iterator
  30829. var i; // point iterator
  30830. var j; // point iterator
  30831. // if single path in pathArray
  30832. if (pathArray.length < 2) {
  30833. var ar1 = [];
  30834. var ar2 = [];
  30835. for (i = 0; i < pathArray[0].length - offset; i++) {
  30836. ar1.push(pathArray[0][i]);
  30837. ar2.push(pathArray[0][i + offset]);
  30838. }
  30839. pathArray = [ar1, ar2];
  30840. }
  30841. // positions and horizontal distances (u)
  30842. var idc = 0;
  30843. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30844. var path;
  30845. var l;
  30846. minlg = pathArray[0].length;
  30847. var vectlg;
  30848. var dist;
  30849. for (p = 0; p < pathArray.length; p++) {
  30850. uTotalDistance[p] = 0;
  30851. us[p] = [0];
  30852. path = pathArray[p];
  30853. l = path.length;
  30854. minlg = (minlg < l) ? minlg : l;
  30855. j = 0;
  30856. while (j < l) {
  30857. positions.push(path[j].x, path[j].y, path[j].z);
  30858. if (j > 0) {
  30859. vectlg = path[j].subtract(path[j - 1]).length();
  30860. dist = vectlg + uTotalDistance[p];
  30861. us[p].push(dist);
  30862. uTotalDistance[p] = dist;
  30863. }
  30864. j++;
  30865. }
  30866. if (closePath) {
  30867. j--;
  30868. positions.push(path[0].x, path[0].y, path[0].z);
  30869. vectlg = path[j].subtract(path[0]).length();
  30870. dist = vectlg + uTotalDistance[p];
  30871. us[p].push(dist);
  30872. uTotalDistance[p] = dist;
  30873. }
  30874. lg[p] = l + closePathCorr;
  30875. idx[p] = idc;
  30876. idc += (l + closePathCorr);
  30877. }
  30878. // vertical distances (v)
  30879. var path1;
  30880. var path2;
  30881. var vertex1 = null;
  30882. var vertex2 = null;
  30883. for (i = 0; i < minlg + closePathCorr; i++) {
  30884. vTotalDistance[i] = 0;
  30885. vs[i] = [0];
  30886. for (p = 0; p < pathArray.length - 1; p++) {
  30887. path1 = pathArray[p];
  30888. path2 = pathArray[p + 1];
  30889. if (i === minlg) {
  30890. vertex1 = path1[0];
  30891. vertex2 = path2[0];
  30892. }
  30893. else {
  30894. vertex1 = path1[i];
  30895. vertex2 = path2[i];
  30896. }
  30897. vectlg = vertex2.subtract(vertex1).length();
  30898. dist = vectlg + vTotalDistance[i];
  30899. vs[i].push(dist);
  30900. vTotalDistance[i] = dist;
  30901. }
  30902. if (closeArray && vertex2 && vertex1) {
  30903. path1 = pathArray[p];
  30904. path2 = pathArray[0];
  30905. if (i === minlg) {
  30906. vertex2 = path2[0];
  30907. }
  30908. vectlg = vertex2.subtract(vertex1).length();
  30909. dist = vectlg + vTotalDistance[i];
  30910. vTotalDistance[i] = dist;
  30911. }
  30912. }
  30913. // uvs
  30914. var u;
  30915. var v;
  30916. if (customUV) {
  30917. for (p = 0; p < customUV.length; p++) {
  30918. uvs.push(customUV[p].x, customUV[p].y);
  30919. }
  30920. }
  30921. else {
  30922. for (p = 0; p < pathArray.length; p++) {
  30923. for (i = 0; i < minlg + closePathCorr; i++) {
  30924. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30925. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30926. if (invertUV) {
  30927. uvs.push(v, u);
  30928. }
  30929. else {
  30930. uvs.push(u, v);
  30931. }
  30932. }
  30933. }
  30934. }
  30935. // indices
  30936. p = 0; // path index
  30937. var pi = 0; // positions array index
  30938. var l1 = lg[p] - 1; // path1 length
  30939. var l2 = lg[p + 1] - 1; // path2 length
  30940. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30941. var shft = idx[1] - idx[0]; // shift
  30942. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30943. while (pi <= min && p < path1nb) {
  30944. // 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
  30945. indices.push(pi, pi + shft, pi + 1);
  30946. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30947. pi += 1;
  30948. if (pi === min) {
  30949. p++;
  30950. if (p === lg.length - 1) {
  30951. shft = idx[0] - idx[p];
  30952. l1 = lg[p] - 1;
  30953. l2 = lg[0] - 1;
  30954. }
  30955. else {
  30956. shft = idx[p + 1] - idx[p];
  30957. l1 = lg[p] - 1;
  30958. l2 = lg[p + 1] - 1;
  30959. }
  30960. pi = idx[p];
  30961. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30962. }
  30963. }
  30964. // normals
  30965. VertexData.ComputeNormals(positions, indices, normals);
  30966. if (closePath) {
  30967. var indexFirst = 0;
  30968. var indexLast = 0;
  30969. for (p = 0; p < pathArray.length; p++) {
  30970. indexFirst = idx[p] * 3;
  30971. if (p + 1 < pathArray.length) {
  30972. indexLast = (idx[p + 1] - 1) * 3;
  30973. }
  30974. else {
  30975. indexLast = normals.length - 3;
  30976. }
  30977. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30978. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30979. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30980. normals[indexLast] = normals[indexFirst];
  30981. normals[indexLast + 1] = normals[indexFirst + 1];
  30982. normals[indexLast + 2] = normals[indexFirst + 2];
  30983. }
  30984. }
  30985. // sides
  30986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30987. // Colors
  30988. var colors = null;
  30989. if (customColors) {
  30990. colors = new Float32Array(customColors.length * 4);
  30991. for (var c = 0; c < customColors.length; c++) {
  30992. colors[c * 4] = customColors[c].r;
  30993. colors[c * 4 + 1] = customColors[c].g;
  30994. colors[c * 4 + 2] = customColors[c].b;
  30995. colors[c * 4 + 3] = customColors[c].a;
  30996. }
  30997. }
  30998. // Result
  30999. var vertexData = new VertexData();
  31000. var positions32 = new Float32Array(positions);
  31001. var normals32 = new Float32Array(normals);
  31002. var uvs32 = new Float32Array(uvs);
  31003. vertexData.indices = indices;
  31004. vertexData.positions = positions32;
  31005. vertexData.normals = normals32;
  31006. vertexData.uvs = uvs32;
  31007. if (colors) {
  31008. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  31009. }
  31010. if (closePath) {
  31011. vertexData._idx = idx;
  31012. }
  31013. return vertexData;
  31014. };
  31015. /**
  31016. * Creates the VertexData of the Box.
  31017. */
  31018. VertexData.CreateBox = function (options) {
  31019. var normalsSource = [
  31020. new BABYLON.Vector3(0, 0, 1),
  31021. new BABYLON.Vector3(0, 0, -1),
  31022. new BABYLON.Vector3(1, 0, 0),
  31023. new BABYLON.Vector3(-1, 0, 0),
  31024. new BABYLON.Vector3(0, 1, 0),
  31025. new BABYLON.Vector3(0, -1, 0)
  31026. ];
  31027. var indices = [];
  31028. var positions = [];
  31029. var normals = [];
  31030. var uvs = [];
  31031. var width = options.width || options.size || 1;
  31032. var height = options.height || options.size || 1;
  31033. var depth = options.depth || options.size || 1;
  31034. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31035. var faceUV = options.faceUV || new Array(6);
  31036. var faceColors = options.faceColors;
  31037. var colors = [];
  31038. // default face colors and UV if undefined
  31039. for (var f = 0; f < 6; f++) {
  31040. if (faceUV[f] === undefined) {
  31041. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31042. }
  31043. if (faceColors && faceColors[f] === undefined) {
  31044. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31045. }
  31046. }
  31047. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31048. // Create each face in turn.
  31049. for (var index = 0; index < normalsSource.length; index++) {
  31050. var normal = normalsSource[index];
  31051. // Get two vectors perpendicular to the face normal and to each other.
  31052. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31053. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31054. // Six indices (two triangles) per face.
  31055. var verticesLength = positions.length / 3;
  31056. indices.push(verticesLength);
  31057. indices.push(verticesLength + 1);
  31058. indices.push(verticesLength + 2);
  31059. indices.push(verticesLength);
  31060. indices.push(verticesLength + 2);
  31061. indices.push(verticesLength + 3);
  31062. // Four vertices per face.
  31063. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31064. positions.push(vertex.x, vertex.y, vertex.z);
  31065. normals.push(normal.x, normal.y, normal.z);
  31066. uvs.push(faceUV[index].z, faceUV[index].w);
  31067. if (faceColors) {
  31068. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31069. }
  31070. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31071. positions.push(vertex.x, vertex.y, vertex.z);
  31072. normals.push(normal.x, normal.y, normal.z);
  31073. uvs.push(faceUV[index].x, faceUV[index].w);
  31074. if (faceColors) {
  31075. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31076. }
  31077. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31078. positions.push(vertex.x, vertex.y, vertex.z);
  31079. normals.push(normal.x, normal.y, normal.z);
  31080. uvs.push(faceUV[index].x, faceUV[index].y);
  31081. if (faceColors) {
  31082. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31083. }
  31084. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31085. positions.push(vertex.x, vertex.y, vertex.z);
  31086. normals.push(normal.x, normal.y, normal.z);
  31087. uvs.push(faceUV[index].z, faceUV[index].y);
  31088. if (faceColors) {
  31089. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31090. }
  31091. }
  31092. // sides
  31093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31094. // Result
  31095. var vertexData = new VertexData();
  31096. vertexData.indices = indices;
  31097. vertexData.positions = positions;
  31098. vertexData.normals = normals;
  31099. vertexData.uvs = uvs;
  31100. if (faceColors) {
  31101. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31102. vertexData.colors = totalColors;
  31103. }
  31104. return vertexData;
  31105. };
  31106. /**
  31107. * Creates the VertexData of the Sphere.
  31108. */
  31109. VertexData.CreateSphere = function (options) {
  31110. var segments = options.segments || 32;
  31111. var diameterX = options.diameterX || options.diameter || 1;
  31112. var diameterY = options.diameterY || options.diameter || 1;
  31113. var diameterZ = options.diameterZ || options.diameter || 1;
  31114. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31115. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31117. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31118. var totalZRotationSteps = 2 + segments;
  31119. var totalYRotationSteps = 2 * totalZRotationSteps;
  31120. var indices = [];
  31121. var positions = [];
  31122. var normals = [];
  31123. var uvs = [];
  31124. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31125. var normalizedZ = zRotationStep / totalZRotationSteps;
  31126. var angleZ = normalizedZ * Math.PI * slice;
  31127. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31128. var normalizedY = yRotationStep / totalYRotationSteps;
  31129. var angleY = normalizedY * Math.PI * 2 * arc;
  31130. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31131. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31132. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31133. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31134. var vertex = complete.multiply(radius);
  31135. var normal = complete.divide(radius).normalize();
  31136. positions.push(vertex.x, vertex.y, vertex.z);
  31137. normals.push(normal.x, normal.y, normal.z);
  31138. uvs.push(normalizedY, normalizedZ);
  31139. }
  31140. if (zRotationStep > 0) {
  31141. var verticesCount = positions.length / 3;
  31142. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31143. indices.push((firstIndex));
  31144. indices.push((firstIndex + 1));
  31145. indices.push(firstIndex + totalYRotationSteps + 1);
  31146. indices.push((firstIndex + totalYRotationSteps + 1));
  31147. indices.push((firstIndex + 1));
  31148. indices.push((firstIndex + totalYRotationSteps + 2));
  31149. }
  31150. }
  31151. }
  31152. // Sides
  31153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31154. // Result
  31155. var vertexData = new VertexData();
  31156. vertexData.indices = indices;
  31157. vertexData.positions = positions;
  31158. vertexData.normals = normals;
  31159. vertexData.uvs = uvs;
  31160. return vertexData;
  31161. };
  31162. /**
  31163. * Creates the VertexData of the Cylinder or Cone.
  31164. */
  31165. VertexData.CreateCylinder = function (options) {
  31166. var height = options.height || 2;
  31167. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31168. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31169. var tessellation = options.tessellation || 24;
  31170. var subdivisions = options.subdivisions || 1;
  31171. var hasRings = options.hasRings ? true : false;
  31172. var enclose = options.enclose ? true : false;
  31173. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31174. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31175. var faceUV = options.faceUV || new Array(3);
  31176. var faceColors = options.faceColors;
  31177. // default face colors and UV if undefined
  31178. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31179. var ringNb = (hasRings) ? subdivisions : 1;
  31180. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31181. var f;
  31182. for (f = 0; f < surfaceNb; f++) {
  31183. if (faceColors && faceColors[f] === undefined) {
  31184. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31185. }
  31186. }
  31187. for (f = 0; f < surfaceNb; f++) {
  31188. if (faceUV && faceUV[f] === undefined) {
  31189. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31190. }
  31191. }
  31192. var indices = new Array();
  31193. var positions = new Array();
  31194. var normals = new Array();
  31195. var uvs = new Array();
  31196. var colors = new Array();
  31197. var angle_step = Math.PI * 2 * arc / tessellation;
  31198. var angle;
  31199. var h;
  31200. var radius;
  31201. var tan = (diameterBottom - diameterTop) / 2 / height;
  31202. var ringVertex = BABYLON.Vector3.Zero();
  31203. var ringNormal = BABYLON.Vector3.Zero();
  31204. var ringFirstVertex = BABYLON.Vector3.Zero();
  31205. var ringFirstNormal = BABYLON.Vector3.Zero();
  31206. var quadNormal = BABYLON.Vector3.Zero();
  31207. var Y = BABYLON.Axis.Y;
  31208. // positions, normals, uvs
  31209. var i;
  31210. var j;
  31211. var r;
  31212. var ringIdx = 1;
  31213. var s = 1; // surface index
  31214. var cs = 0;
  31215. var v = 0;
  31216. for (i = 0; i <= subdivisions; i++) {
  31217. h = i / subdivisions;
  31218. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31219. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31220. for (r = 0; r < ringIdx; r++) {
  31221. if (hasRings) {
  31222. s += r;
  31223. }
  31224. if (enclose) {
  31225. s += 2 * r;
  31226. }
  31227. for (j = 0; j <= tessellation; j++) {
  31228. angle = j * angle_step;
  31229. // position
  31230. ringVertex.x = Math.cos(-angle) * radius;
  31231. ringVertex.y = -height / 2 + h * height;
  31232. ringVertex.z = Math.sin(-angle) * radius;
  31233. // normal
  31234. if (diameterTop === 0 && i === subdivisions) {
  31235. // if no top cap, reuse former normals
  31236. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31237. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31238. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31239. }
  31240. else {
  31241. ringNormal.x = ringVertex.x;
  31242. ringNormal.z = ringVertex.z;
  31243. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31244. ringNormal.normalize();
  31245. }
  31246. // keep first ring vertex values for enclose
  31247. if (j === 0) {
  31248. ringFirstVertex.copyFrom(ringVertex);
  31249. ringFirstNormal.copyFrom(ringNormal);
  31250. }
  31251. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31252. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31253. if (hasRings) {
  31254. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31255. }
  31256. else {
  31257. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31258. }
  31259. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31260. if (faceColors) {
  31261. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31262. }
  31263. }
  31264. // if enclose, add four vertices and their dedicated normals
  31265. if (arc !== 1 && enclose) {
  31266. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31267. positions.push(0, ringVertex.y, 0);
  31268. positions.push(0, ringVertex.y, 0);
  31269. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31270. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31271. quadNormal.normalize();
  31272. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31273. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31274. quadNormal.normalize();
  31275. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31276. if (hasRings) {
  31277. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31278. }
  31279. else {
  31280. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31281. }
  31282. uvs.push(faceUV[s + 1].x, v);
  31283. uvs.push(faceUV[s + 1].z, v);
  31284. if (hasRings) {
  31285. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31286. }
  31287. else {
  31288. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31289. }
  31290. uvs.push(faceUV[s + 2].x, v);
  31291. uvs.push(faceUV[s + 2].z, v);
  31292. if (faceColors) {
  31293. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31294. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31295. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31296. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31297. }
  31298. }
  31299. if (cs !== s) {
  31300. cs = s;
  31301. }
  31302. }
  31303. }
  31304. // indices
  31305. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31306. var s;
  31307. i = 0;
  31308. for (s = 0; s < subdivisions; s++) {
  31309. var i0 = 0;
  31310. var i1 = 0;
  31311. var i2 = 0;
  31312. var i3 = 0;
  31313. for (j = 0; j < tessellation; j++) {
  31314. i0 = i * (e + 1) + j;
  31315. i1 = (i + 1) * (e + 1) + j;
  31316. i2 = i * (e + 1) + (j + 1);
  31317. i3 = (i + 1) * (e + 1) + (j + 1);
  31318. indices.push(i0, i1, i2);
  31319. indices.push(i3, i2, i1);
  31320. }
  31321. if (arc !== 1 && enclose) {
  31322. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31323. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31324. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31325. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31326. }
  31327. i = (hasRings) ? (i + 2) : (i + 1);
  31328. }
  31329. // Caps
  31330. var createCylinderCap = function (isTop) {
  31331. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31332. if (radius === 0) {
  31333. return;
  31334. }
  31335. // Cap positions, normals & uvs
  31336. var angle;
  31337. var circleVector;
  31338. var i;
  31339. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31340. var c = null;
  31341. if (faceColors) {
  31342. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31343. }
  31344. // cap center
  31345. var vbase = positions.length / 3;
  31346. var offset = isTop ? height / 2 : -height / 2;
  31347. var center = new BABYLON.Vector3(0, offset, 0);
  31348. positions.push(center.x, center.y, center.z);
  31349. normals.push(0, isTop ? 1 : -1, 0);
  31350. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31351. if (c) {
  31352. colors.push(c.r, c.g, c.b, c.a);
  31353. }
  31354. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31355. for (i = 0; i <= tessellation; i++) {
  31356. angle = Math.PI * 2 * i * arc / tessellation;
  31357. var cos = Math.cos(-angle);
  31358. var sin = Math.sin(-angle);
  31359. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31360. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31361. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31362. normals.push(0, isTop ? 1 : -1, 0);
  31363. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31364. if (c) {
  31365. colors.push(c.r, c.g, c.b, c.a);
  31366. }
  31367. }
  31368. // Cap indices
  31369. for (i = 0; i < tessellation; i++) {
  31370. if (!isTop) {
  31371. indices.push(vbase);
  31372. indices.push(vbase + (i + 1));
  31373. indices.push(vbase + (i + 2));
  31374. }
  31375. else {
  31376. indices.push(vbase);
  31377. indices.push(vbase + (i + 2));
  31378. indices.push(vbase + (i + 1));
  31379. }
  31380. }
  31381. };
  31382. // add caps to geometry
  31383. createCylinderCap(false);
  31384. createCylinderCap(true);
  31385. // Sides
  31386. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31387. var vertexData = new VertexData();
  31388. vertexData.indices = indices;
  31389. vertexData.positions = positions;
  31390. vertexData.normals = normals;
  31391. vertexData.uvs = uvs;
  31392. if (faceColors) {
  31393. vertexData.colors = colors;
  31394. }
  31395. return vertexData;
  31396. };
  31397. /**
  31398. * Creates the VertexData of the Torus.
  31399. */
  31400. VertexData.CreateTorus = function (options) {
  31401. var indices = [];
  31402. var positions = [];
  31403. var normals = [];
  31404. var uvs = [];
  31405. var diameter = options.diameter || 1;
  31406. var thickness = options.thickness || 0.5;
  31407. var tessellation = options.tessellation || 16;
  31408. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31409. var stride = tessellation + 1;
  31410. for (var i = 0; i <= tessellation; i++) {
  31411. var u = i / tessellation;
  31412. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31413. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31414. for (var j = 0; j <= tessellation; j++) {
  31415. var v = 1 - j / tessellation;
  31416. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31417. var dx = Math.cos(innerAngle);
  31418. var dy = Math.sin(innerAngle);
  31419. // Create a vertex.
  31420. var normal = new BABYLON.Vector3(dx, dy, 0);
  31421. var position = normal.scale(thickness / 2);
  31422. var textureCoordinate = new BABYLON.Vector2(u, v);
  31423. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31424. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31425. positions.push(position.x, position.y, position.z);
  31426. normals.push(normal.x, normal.y, normal.z);
  31427. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31428. // And create indices for two triangles.
  31429. var nextI = (i + 1) % stride;
  31430. var nextJ = (j + 1) % stride;
  31431. indices.push(i * stride + j);
  31432. indices.push(i * stride + nextJ);
  31433. indices.push(nextI * stride + j);
  31434. indices.push(i * stride + nextJ);
  31435. indices.push(nextI * stride + nextJ);
  31436. indices.push(nextI * stride + j);
  31437. }
  31438. }
  31439. // Sides
  31440. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31441. // Result
  31442. var vertexData = new VertexData();
  31443. vertexData.indices = indices;
  31444. vertexData.positions = positions;
  31445. vertexData.normals = normals;
  31446. vertexData.uvs = uvs;
  31447. return vertexData;
  31448. };
  31449. /**
  31450. * Creates the VertexData of the LineSystem.
  31451. */
  31452. VertexData.CreateLineSystem = function (options) {
  31453. var indices = [];
  31454. var positions = [];
  31455. var lines = options.lines;
  31456. var colors = options.colors;
  31457. var vertexColors = [];
  31458. var idx = 0;
  31459. for (var l = 0; l < lines.length; l++) {
  31460. var points = lines[l];
  31461. for (var index = 0; index < points.length; index++) {
  31462. positions.push(points[index].x, points[index].y, points[index].z);
  31463. if (colors) {
  31464. var color = colors[l];
  31465. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31466. }
  31467. if (index > 0) {
  31468. indices.push(idx - 1);
  31469. indices.push(idx);
  31470. }
  31471. idx++;
  31472. }
  31473. }
  31474. var vertexData = new VertexData();
  31475. vertexData.indices = indices;
  31476. vertexData.positions = positions;
  31477. if (colors) {
  31478. vertexData.colors = vertexColors;
  31479. }
  31480. return vertexData;
  31481. };
  31482. /**
  31483. * Create the VertexData of the DashedLines.
  31484. */
  31485. VertexData.CreateDashedLines = function (options) {
  31486. var dashSize = options.dashSize || 3;
  31487. var gapSize = options.gapSize || 1;
  31488. var dashNb = options.dashNb || 200;
  31489. var points = options.points;
  31490. var positions = new Array();
  31491. var indices = new Array();
  31492. var curvect = BABYLON.Vector3.Zero();
  31493. var lg = 0;
  31494. var nb = 0;
  31495. var shft = 0;
  31496. var dashshft = 0;
  31497. var curshft = 0;
  31498. var idx = 0;
  31499. var i = 0;
  31500. for (i = 0; i < points.length - 1; i++) {
  31501. points[i + 1].subtractToRef(points[i], curvect);
  31502. lg += curvect.length();
  31503. }
  31504. shft = lg / dashNb;
  31505. dashshft = dashSize * shft / (dashSize + gapSize);
  31506. for (i = 0; i < points.length - 1; i++) {
  31507. points[i + 1].subtractToRef(points[i], curvect);
  31508. nb = Math.floor(curvect.length() / shft);
  31509. curvect.normalize();
  31510. for (var j = 0; j < nb; j++) {
  31511. curshft = shft * j;
  31512. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31513. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31514. indices.push(idx, idx + 1);
  31515. idx += 2;
  31516. }
  31517. }
  31518. // Result
  31519. var vertexData = new VertexData();
  31520. vertexData.positions = positions;
  31521. vertexData.indices = indices;
  31522. return vertexData;
  31523. };
  31524. /**
  31525. * Creates the VertexData of the Ground.
  31526. */
  31527. VertexData.CreateGround = function (options) {
  31528. var indices = [];
  31529. var positions = [];
  31530. var normals = [];
  31531. var uvs = [];
  31532. var row, col;
  31533. var width = options.width || 1;
  31534. var height = options.height || 1;
  31535. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31536. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31537. for (row = 0; row <= subdivisionsY; row++) {
  31538. for (col = 0; col <= subdivisionsX; col++) {
  31539. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31540. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31541. positions.push(position.x, position.y, position.z);
  31542. normals.push(normal.x, normal.y, normal.z);
  31543. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31544. }
  31545. }
  31546. for (row = 0; row < subdivisionsY; row++) {
  31547. for (col = 0; col < subdivisionsX; col++) {
  31548. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31549. indices.push(col + 1 + row * (subdivisionsX + 1));
  31550. indices.push(col + row * (subdivisionsX + 1));
  31551. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31552. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31553. indices.push(col + row * (subdivisionsX + 1));
  31554. }
  31555. }
  31556. // Result
  31557. var vertexData = new VertexData();
  31558. vertexData.indices = indices;
  31559. vertexData.positions = positions;
  31560. vertexData.normals = normals;
  31561. vertexData.uvs = uvs;
  31562. return vertexData;
  31563. };
  31564. /**
  31565. * Creates the VertexData of the TiledGround.
  31566. */
  31567. VertexData.CreateTiledGround = function (options) {
  31568. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31569. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31570. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31571. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31572. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31573. var precision = options.precision || { w: 1, h: 1 };
  31574. var indices = new Array();
  31575. var positions = new Array();
  31576. var normals = new Array();
  31577. var uvs = new Array();
  31578. var row, col, tileRow, tileCol;
  31579. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31580. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31581. precision.w = (precision.w < 1) ? 1 : precision.w;
  31582. precision.h = (precision.h < 1) ? 1 : precision.h;
  31583. var tileSize = {
  31584. 'w': (xmax - xmin) / subdivisions.w,
  31585. 'h': (zmax - zmin) / subdivisions.h
  31586. };
  31587. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31588. // Indices
  31589. var base = positions.length / 3;
  31590. var rowLength = precision.w + 1;
  31591. for (row = 0; row < precision.h; row++) {
  31592. for (col = 0; col < precision.w; col++) {
  31593. var square = [
  31594. base + col + row * rowLength,
  31595. base + (col + 1) + row * rowLength,
  31596. base + (col + 1) + (row + 1) * rowLength,
  31597. base + col + (row + 1) * rowLength
  31598. ];
  31599. indices.push(square[1]);
  31600. indices.push(square[2]);
  31601. indices.push(square[3]);
  31602. indices.push(square[0]);
  31603. indices.push(square[1]);
  31604. indices.push(square[3]);
  31605. }
  31606. }
  31607. // Position, normals and uvs
  31608. var position = BABYLON.Vector3.Zero();
  31609. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31610. for (row = 0; row <= precision.h; row++) {
  31611. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31612. for (col = 0; col <= precision.w; col++) {
  31613. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31614. position.y = 0;
  31615. positions.push(position.x, position.y, position.z);
  31616. normals.push(normal.x, normal.y, normal.z);
  31617. uvs.push(col / precision.w, row / precision.h);
  31618. }
  31619. }
  31620. }
  31621. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31622. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31623. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31624. }
  31625. }
  31626. // Result
  31627. var vertexData = new VertexData();
  31628. vertexData.indices = indices;
  31629. vertexData.positions = positions;
  31630. vertexData.normals = normals;
  31631. vertexData.uvs = uvs;
  31632. return vertexData;
  31633. };
  31634. /**
  31635. * Creates the VertexData of the Ground designed from a heightmap.
  31636. */
  31637. VertexData.CreateGroundFromHeightMap = function (options) {
  31638. var indices = [];
  31639. var positions = [];
  31640. var normals = [];
  31641. var uvs = [];
  31642. var row, col;
  31643. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31644. // Vertices
  31645. for (row = 0; row <= options.subdivisions; row++) {
  31646. for (col = 0; col <= options.subdivisions; col++) {
  31647. 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));
  31648. // Compute height
  31649. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31650. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31651. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31652. var r = options.buffer[pos] / 255.0;
  31653. var g = options.buffer[pos + 1] / 255.0;
  31654. var b = options.buffer[pos + 2] / 255.0;
  31655. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31656. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31657. // Add vertex
  31658. positions.push(position.x, position.y, position.z);
  31659. normals.push(0, 0, 0);
  31660. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31661. }
  31662. }
  31663. // Indices
  31664. for (row = 0; row < options.subdivisions; row++) {
  31665. for (col = 0; col < options.subdivisions; col++) {
  31666. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31667. indices.push(col + 1 + row * (options.subdivisions + 1));
  31668. indices.push(col + row * (options.subdivisions + 1));
  31669. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31670. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31671. indices.push(col + row * (options.subdivisions + 1));
  31672. }
  31673. }
  31674. // Normals
  31675. VertexData.ComputeNormals(positions, indices, normals);
  31676. // Result
  31677. var vertexData = new VertexData();
  31678. vertexData.indices = indices;
  31679. vertexData.positions = positions;
  31680. vertexData.normals = normals;
  31681. vertexData.uvs = uvs;
  31682. return vertexData;
  31683. };
  31684. /**
  31685. * Creates the VertexData of the Plane.
  31686. */
  31687. VertexData.CreatePlane = function (options) {
  31688. var indices = [];
  31689. var positions = [];
  31690. var normals = [];
  31691. var uvs = [];
  31692. var width = options.width || options.size || 1;
  31693. var height = options.height || options.size || 1;
  31694. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31695. // Vertices
  31696. var halfWidth = width / 2.0;
  31697. var halfHeight = height / 2.0;
  31698. positions.push(-halfWidth, -halfHeight, 0);
  31699. normals.push(0, 0, -1.0);
  31700. uvs.push(0.0, 0.0);
  31701. positions.push(halfWidth, -halfHeight, 0);
  31702. normals.push(0, 0, -1.0);
  31703. uvs.push(1.0, 0.0);
  31704. positions.push(halfWidth, halfHeight, 0);
  31705. normals.push(0, 0, -1.0);
  31706. uvs.push(1.0, 1.0);
  31707. positions.push(-halfWidth, halfHeight, 0);
  31708. normals.push(0, 0, -1.0);
  31709. uvs.push(0.0, 1.0);
  31710. // Indices
  31711. indices.push(0);
  31712. indices.push(1);
  31713. indices.push(2);
  31714. indices.push(0);
  31715. indices.push(2);
  31716. indices.push(3);
  31717. // Sides
  31718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31719. // Result
  31720. var vertexData = new VertexData();
  31721. vertexData.indices = indices;
  31722. vertexData.positions = positions;
  31723. vertexData.normals = normals;
  31724. vertexData.uvs = uvs;
  31725. return vertexData;
  31726. };
  31727. /**
  31728. * Creates the VertexData of the Disc or regular Polygon.
  31729. */
  31730. VertexData.CreateDisc = function (options) {
  31731. var positions = new Array();
  31732. var indices = new Array();
  31733. var normals = new Array();
  31734. var uvs = new Array();
  31735. var radius = options.radius || 0.5;
  31736. var tessellation = options.tessellation || 64;
  31737. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31738. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31739. // positions and uvs
  31740. positions.push(0, 0, 0); // disc center first
  31741. uvs.push(0.5, 0.5);
  31742. var theta = Math.PI * 2 * arc;
  31743. var step = theta / tessellation;
  31744. for (var a = 0; a < theta; a += step) {
  31745. var x = Math.cos(a);
  31746. var y = Math.sin(a);
  31747. var u = (x + 1) / 2;
  31748. var v = (1 - y) / 2;
  31749. positions.push(radius * x, radius * y, 0);
  31750. uvs.push(u, v);
  31751. }
  31752. if (arc === 1) {
  31753. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31754. uvs.push(uvs[2], uvs[3]);
  31755. }
  31756. //indices
  31757. var vertexNb = positions.length / 3;
  31758. for (var i = 1; i < vertexNb - 1; i++) {
  31759. indices.push(i + 1, 0, i);
  31760. }
  31761. // result
  31762. VertexData.ComputeNormals(positions, indices, normals);
  31763. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31764. var vertexData = new VertexData();
  31765. vertexData.indices = indices;
  31766. vertexData.positions = positions;
  31767. vertexData.normals = normals;
  31768. vertexData.uvs = uvs;
  31769. return vertexData;
  31770. };
  31771. /**
  31772. * Re-creates the VertexData of the Polygon for sideOrientation.
  31773. */
  31774. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31775. var faceUV = fUV || new Array(3);
  31776. var faceColors = fColors;
  31777. var colors = [];
  31778. // default face colors and UV if undefined
  31779. for (var f = 0; f < 3; f++) {
  31780. if (faceUV[f] === undefined) {
  31781. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31782. }
  31783. if (faceColors && faceColors[f] === undefined) {
  31784. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31785. }
  31786. }
  31787. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31788. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31789. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31790. var indices = polygon.getIndices();
  31791. // set face colours and textures
  31792. var idx = 0;
  31793. var face = 0;
  31794. for (var index = 0; index < normals.length; index += 3) {
  31795. //Edge Face no. 1
  31796. if (Math.abs(normals[index + 1]) < 0.001) {
  31797. face = 1;
  31798. }
  31799. //Top Face no. 0
  31800. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31801. face = 0;
  31802. }
  31803. //Bottom Face no. 2
  31804. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31805. face = 2;
  31806. }
  31807. idx = index / 3;
  31808. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31809. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31810. if (faceColors) {
  31811. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31812. }
  31813. }
  31814. // sides
  31815. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31816. // Result
  31817. var vertexData = new VertexData();
  31818. vertexData.indices = indices;
  31819. vertexData.positions = positions;
  31820. vertexData.normals = normals;
  31821. vertexData.uvs = uvs;
  31822. if (faceColors) {
  31823. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31824. vertexData.colors = totalColors;
  31825. }
  31826. return vertexData;
  31827. };
  31828. /**
  31829. * Creates the VertexData of the IcoSphere.
  31830. */
  31831. VertexData.CreateIcoSphere = function (options) {
  31832. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31833. var radius = options.radius || 1;
  31834. var flat = (options.flat === undefined) ? true : options.flat;
  31835. var subdivisions = options.subdivisions || 4;
  31836. var radiusX = options.radiusX || radius;
  31837. var radiusY = options.radiusY || radius;
  31838. var radiusZ = options.radiusZ || radius;
  31839. var t = (1 + Math.sqrt(5)) / 2;
  31840. // 12 vertex x,y,z
  31841. var ico_vertices = [
  31842. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31843. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31844. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31845. ];
  31846. // index of 3 vertex makes a face of icopshere
  31847. var ico_indices = [
  31848. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31849. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31850. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31851. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31852. ];
  31853. // vertex for uv have aliased position, not for UV
  31854. var vertices_unalias_id = [
  31855. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31856. // vertex alias
  31857. 0,
  31858. 2,
  31859. 3,
  31860. 3,
  31861. 3,
  31862. 4,
  31863. 7,
  31864. 8,
  31865. 9,
  31866. 9,
  31867. 10,
  31868. 11 // 23: B + 12
  31869. ];
  31870. // uv as integer step (not pixels !)
  31871. var ico_vertexuv = [
  31872. 5, 1, 3, 1, 6, 4, 0, 0,
  31873. 5, 3, 4, 2, 2, 2, 4, 0,
  31874. 2, 0, 1, 1, 6, 0, 6, 2,
  31875. // vertex alias (for same vertex on different faces)
  31876. 0, 4,
  31877. 3, 3,
  31878. 4, 4,
  31879. 3, 1,
  31880. 4, 2,
  31881. 4, 4,
  31882. 0, 2,
  31883. 1, 1,
  31884. 2, 2,
  31885. 3, 3,
  31886. 1, 3,
  31887. 2, 4 // 23: B + 12
  31888. ];
  31889. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31890. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31891. // First island of uv mapping
  31892. // v = 4h 3+ 2
  31893. // v = 3h 9+ 4
  31894. // v = 2h 9+ 5 B
  31895. // v = 1h 9 1 0
  31896. // v = 0h 3 8 7 A
  31897. // u = 0 1 2 3 4 5 6 *a
  31898. // Second island of uv mapping
  31899. // v = 4h 0+ B+ 4+
  31900. // v = 3h A+ 2+
  31901. // v = 2h 7+ 6 3+
  31902. // v = 1h 8+ 3+
  31903. // v = 0h
  31904. // u = 0 1 2 3 4 5 6 *a
  31905. // Face layout on texture UV mapping
  31906. // ============
  31907. // \ 4 /\ 16 / ======
  31908. // \ / \ / /\ 11 /
  31909. // \/ 7 \/ / \ /
  31910. // ======= / 10 \/
  31911. // /\ 17 /\ =======
  31912. // / \ / \ \ 15 /\
  31913. // / 8 \/ 12 \ \ / \
  31914. // ============ \/ 6 \
  31915. // \ 18 /\ ============
  31916. // \ / \ \ 5 /\ 0 /
  31917. // \/ 13 \ \ / \ /
  31918. // ======= \/ 1 \/
  31919. // =============
  31920. // /\ 19 /\ 2 /\
  31921. // / \ / \ / \
  31922. // / 14 \/ 9 \/ 3 \
  31923. // ===================
  31924. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31925. var ustep = 138 / 1024;
  31926. var vstep = 239 / 1024;
  31927. var uoffset = 60 / 1024;
  31928. var voffset = 26 / 1024;
  31929. // Second island should have margin, not to touch the first island
  31930. // avoid any borderline artefact in pixel rounding
  31931. var island_u_offset = -40 / 1024;
  31932. var island_v_offset = +20 / 1024;
  31933. // face is either island 0 or 1 :
  31934. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31935. var island = [
  31936. 0, 0, 0, 0, 1,
  31937. 0, 0, 1, 1, 0,
  31938. 0, 0, 1, 1, 0,
  31939. 0, 1, 1, 1, 0 // 15 - 19
  31940. ];
  31941. var indices = new Array();
  31942. var positions = new Array();
  31943. var normals = new Array();
  31944. var uvs = new Array();
  31945. var current_indice = 0;
  31946. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31947. var face_vertex_pos = new Array(3);
  31948. var face_vertex_uv = new Array(3);
  31949. var v012;
  31950. for (v012 = 0; v012 < 3; v012++) {
  31951. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31952. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31953. }
  31954. // create all with normals
  31955. for (var face = 0; face < 20; face++) {
  31956. // 3 vertex per face
  31957. for (v012 = 0; v012 < 3; v012++) {
  31958. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31959. var v_id = ico_indices[3 * face + v012];
  31960. // vertex have 3D position (x,y,z)
  31961. 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]);
  31962. // Normalize to get normal, then scale to radius
  31963. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31964. // uv Coordinates from vertex ID
  31965. 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);
  31966. }
  31967. // Subdivide the face (interpolate pos, norm, uv)
  31968. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31969. // - norm is linear interpolation of vertex corner normal
  31970. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31971. // - uv is linear interpolation
  31972. //
  31973. // Topology is as below for sub-divide by 2
  31974. // vertex shown as v0,v1,v2
  31975. // interp index is i1 to progress in range [v0,v1[
  31976. // interp index is i2 to progress in range [v0,v2[
  31977. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31978. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31979. //
  31980. //
  31981. // i2 v2
  31982. // ^ ^
  31983. // / / \
  31984. // / / \
  31985. // / / \
  31986. // / / (0,1) \
  31987. // / #---------\
  31988. // / / \ (0,0)'/ \
  31989. // / / \ / \
  31990. // / / \ / \
  31991. // / / (0,0) \ / (1,0) \
  31992. // / #---------#---------\
  31993. // v0 v1
  31994. //
  31995. // --------------------> i1
  31996. //
  31997. // interp of (i1,i2):
  31998. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31999. // along i1 : lerp(x0,x1, i1/(S-i2))
  32000. //
  32001. // centroid of triangle is needed to get help normal computation
  32002. // (c1,c2) are used for centroid location
  32003. var interp_vertex = function (i1, i2, c1, c2) {
  32004. // vertex is interpolated from
  32005. // - face_vertex_pos[0..2]
  32006. // - face_vertex_uv[0..2]
  32007. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32008. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32009. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32010. pos_interp.normalize();
  32011. var vertex_normal;
  32012. if (flat) {
  32013. // in flat mode, recalculate normal as face centroid normal
  32014. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32015. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32016. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32017. }
  32018. else {
  32019. // in smooth mode, recalculate normal from each single vertex position
  32020. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32021. }
  32022. // Vertex normal need correction due to X,Y,Z radius scaling
  32023. vertex_normal.x /= radiusX;
  32024. vertex_normal.y /= radiusY;
  32025. vertex_normal.z /= radiusZ;
  32026. vertex_normal.normalize();
  32027. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32028. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32029. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32030. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32031. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32032. uvs.push(uv_interp.x, uv_interp.y);
  32033. // push each vertex has member of a face
  32034. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32035. indices.push(current_indice);
  32036. current_indice++;
  32037. };
  32038. for (var i2 = 0; i2 < subdivisions; i2++) {
  32039. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32040. // face : (i1,i2) for /\ :
  32041. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32042. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32043. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32044. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32045. if (i1 + i2 + 1 < subdivisions) {
  32046. // face : (i1,i2)' for \/ :
  32047. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32048. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32049. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32050. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32051. }
  32052. }
  32053. }
  32054. }
  32055. // Sides
  32056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32057. // Result
  32058. var vertexData = new VertexData();
  32059. vertexData.indices = indices;
  32060. vertexData.positions = positions;
  32061. vertexData.normals = normals;
  32062. vertexData.uvs = uvs;
  32063. return vertexData;
  32064. };
  32065. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32066. /**
  32067. * Creates the VertexData of the Polyhedron.
  32068. */
  32069. VertexData.CreatePolyhedron = function (options) {
  32070. // provided polyhedron types :
  32071. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32072. // 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)
  32073. var polyhedra = [];
  32074. 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]] };
  32075. 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]] };
  32076. polyhedra[2] = {
  32077. 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]],
  32078. 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]]
  32079. };
  32080. polyhedra[3] = {
  32081. 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]],
  32082. 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]]
  32083. };
  32084. polyhedra[4] = {
  32085. 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]],
  32086. 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]]
  32087. };
  32088. 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]] };
  32089. 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]] };
  32090. 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]] };
  32091. 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]] };
  32092. 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]] };
  32093. 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]] };
  32094. 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]] };
  32095. 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]] };
  32096. 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]] };
  32097. polyhedra[14] = {
  32098. 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]],
  32099. 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]]
  32100. };
  32101. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32102. var size = options.size;
  32103. var sizeX = options.sizeX || size || 1;
  32104. var sizeY = options.sizeY || size || 1;
  32105. var sizeZ = options.sizeZ || size || 1;
  32106. var data = options.custom || polyhedra[type];
  32107. var nbfaces = data.face.length;
  32108. var faceUV = options.faceUV || new Array(nbfaces);
  32109. var faceColors = options.faceColors;
  32110. var flat = (options.flat === undefined) ? true : options.flat;
  32111. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32112. var positions = new Array();
  32113. var indices = new Array();
  32114. var normals = new Array();
  32115. var uvs = new Array();
  32116. var colors = new Array();
  32117. var index = 0;
  32118. var faceIdx = 0; // face cursor in the array "indexes"
  32119. var indexes = new Array();
  32120. var i = 0;
  32121. var f = 0;
  32122. var u, v, ang, x, y, tmp;
  32123. // default face colors and UV if undefined
  32124. if (flat) {
  32125. for (f = 0; f < nbfaces; f++) {
  32126. if (faceColors && faceColors[f] === undefined) {
  32127. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32128. }
  32129. if (faceUV && faceUV[f] === undefined) {
  32130. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32131. }
  32132. }
  32133. }
  32134. if (!flat) {
  32135. for (i = 0; i < data.vertex.length; i++) {
  32136. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32137. uvs.push(0, 0);
  32138. }
  32139. for (f = 0; f < nbfaces; f++) {
  32140. for (i = 0; i < data.face[f].length - 2; i++) {
  32141. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32142. }
  32143. }
  32144. }
  32145. else {
  32146. for (f = 0; f < nbfaces; f++) {
  32147. var fl = data.face[f].length; // number of vertices of the current face
  32148. ang = 2 * Math.PI / fl;
  32149. x = 0.5 * Math.tan(ang / 2);
  32150. y = 0.5;
  32151. // positions, uvs, colors
  32152. for (i = 0; i < fl; i++) {
  32153. // positions
  32154. 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);
  32155. indexes.push(index);
  32156. index++;
  32157. // uvs
  32158. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32159. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32160. uvs.push(u, v);
  32161. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32162. y = x * Math.sin(ang) + y * Math.cos(ang);
  32163. x = tmp;
  32164. // colors
  32165. if (faceColors) {
  32166. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32167. }
  32168. }
  32169. // indices from indexes
  32170. for (i = 0; i < fl - 2; i++) {
  32171. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32172. }
  32173. faceIdx += fl;
  32174. }
  32175. }
  32176. VertexData.ComputeNormals(positions, indices, normals);
  32177. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32178. var vertexData = new VertexData();
  32179. vertexData.positions = positions;
  32180. vertexData.indices = indices;
  32181. vertexData.normals = normals;
  32182. vertexData.uvs = uvs;
  32183. if (faceColors && flat) {
  32184. vertexData.colors = colors;
  32185. }
  32186. return vertexData;
  32187. };
  32188. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32189. /**
  32190. * Creates the VertexData of the Torus Knot.
  32191. */
  32192. VertexData.CreateTorusKnot = function (options) {
  32193. var indices = new Array();
  32194. var positions = new Array();
  32195. var normals = new Array();
  32196. var uvs = new Array();
  32197. var radius = options.radius || 2;
  32198. var tube = options.tube || 0.5;
  32199. var radialSegments = options.radialSegments || 32;
  32200. var tubularSegments = options.tubularSegments || 32;
  32201. var p = options.p || 2;
  32202. var q = options.q || 3;
  32203. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32204. // Helper
  32205. var getPos = function (angle) {
  32206. var cu = Math.cos(angle);
  32207. var su = Math.sin(angle);
  32208. var quOverP = q / p * angle;
  32209. var cs = Math.cos(quOverP);
  32210. var tx = radius * (2 + cs) * 0.5 * cu;
  32211. var ty = radius * (2 + cs) * su * 0.5;
  32212. var tz = radius * Math.sin(quOverP) * 0.5;
  32213. return new BABYLON.Vector3(tx, ty, tz);
  32214. };
  32215. // Vertices
  32216. var i;
  32217. var j;
  32218. for (i = 0; i <= radialSegments; i++) {
  32219. var modI = i % radialSegments;
  32220. var u = modI / radialSegments * 2 * p * Math.PI;
  32221. var p1 = getPos(u);
  32222. var p2 = getPos(u + 0.01);
  32223. var tang = p2.subtract(p1);
  32224. var n = p2.add(p1);
  32225. var bitan = BABYLON.Vector3.Cross(tang, n);
  32226. n = BABYLON.Vector3.Cross(bitan, tang);
  32227. bitan.normalize();
  32228. n.normalize();
  32229. for (j = 0; j < tubularSegments; j++) {
  32230. var modJ = j % tubularSegments;
  32231. var v = modJ / tubularSegments * 2 * Math.PI;
  32232. var cx = -tube * Math.cos(v);
  32233. var cy = tube * Math.sin(v);
  32234. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32235. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32236. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32237. uvs.push(i / radialSegments);
  32238. uvs.push(j / tubularSegments);
  32239. }
  32240. }
  32241. for (i = 0; i < radialSegments; i++) {
  32242. for (j = 0; j < tubularSegments; j++) {
  32243. var jNext = (j + 1) % tubularSegments;
  32244. var a = i * tubularSegments + j;
  32245. var b = (i + 1) * tubularSegments + j;
  32246. var c = (i + 1) * tubularSegments + jNext;
  32247. var d = i * tubularSegments + jNext;
  32248. indices.push(d);
  32249. indices.push(b);
  32250. indices.push(a);
  32251. indices.push(d);
  32252. indices.push(c);
  32253. indices.push(b);
  32254. }
  32255. }
  32256. // Normals
  32257. VertexData.ComputeNormals(positions, indices, normals);
  32258. // Sides
  32259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32260. // Result
  32261. var vertexData = new VertexData();
  32262. vertexData.indices = indices;
  32263. vertexData.positions = positions;
  32264. vertexData.normals = normals;
  32265. vertexData.uvs = uvs;
  32266. return vertexData;
  32267. };
  32268. // Tools
  32269. /**
  32270. * @param {any} - positions (number[] or Float32Array)
  32271. * @param {any} - indices (number[] or Uint16Array)
  32272. * @param {any} - normals (number[] or Float32Array)
  32273. * options (optional) :
  32274. * facetPositions : optional array of facet positions (vector3)
  32275. * facetNormals : optional array of facet normals (vector3)
  32276. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32277. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32278. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32279. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32280. * bInfo : optional bounding info, required for facetPartitioning computation
  32281. * useRightHandedSystem: optional boolean to for right handed system computation
  32282. * depthSort : optional boolean to enable the facet depth sort computation
  32283. * distanceTo : optional Vector3 to compute the facet depth from this location
  32284. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32285. */
  32286. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32287. // temporary scalar variables
  32288. var index = 0; // facet index
  32289. var p1p2x = 0.0; // p1p2 vector x coordinate
  32290. var p1p2y = 0.0; // p1p2 vector y coordinate
  32291. var p1p2z = 0.0; // p1p2 vector z coordinate
  32292. var p3p2x = 0.0; // p3p2 vector x coordinate
  32293. var p3p2y = 0.0; // p3p2 vector y coordinate
  32294. var p3p2z = 0.0; // p3p2 vector z coordinate
  32295. var faceNormalx = 0.0; // facet normal x coordinate
  32296. var faceNormaly = 0.0; // facet normal y coordinate
  32297. var faceNormalz = 0.0; // facet normal z coordinate
  32298. var length = 0.0; // facet normal length before normalization
  32299. var v1x = 0; // vector1 x index in the positions array
  32300. var v1y = 0; // vector1 y index in the positions array
  32301. var v1z = 0; // vector1 z index in the positions array
  32302. var v2x = 0; // vector2 x index in the positions array
  32303. var v2y = 0; // vector2 y index in the positions array
  32304. var v2z = 0; // vector2 z index in the positions array
  32305. var v3x = 0; // vector3 x index in the positions array
  32306. var v3y = 0; // vector3 y index in the positions array
  32307. var v3z = 0; // vector3 z index in the positions array
  32308. var computeFacetNormals = false;
  32309. var computeFacetPositions = false;
  32310. var computeFacetPartitioning = false;
  32311. var computeDepthSort = false;
  32312. var faceNormalSign = 1;
  32313. var ratio = 0;
  32314. var distanceTo = null;
  32315. if (options) {
  32316. computeFacetNormals = (options.facetNormals) ? true : false;
  32317. computeFacetPositions = (options.facetPositions) ? true : false;
  32318. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32319. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32320. ratio = options.ratio || 0;
  32321. computeDepthSort = (options.depthSort) ? true : false;
  32322. distanceTo = (options.distanceTo);
  32323. if (computeDepthSort) {
  32324. if (distanceTo === undefined) {
  32325. distanceTo = BABYLON.Vector3.Zero();
  32326. }
  32327. var depthSortedFacets = options.depthSortedFacets;
  32328. }
  32329. }
  32330. // facetPartitioning reinit if needed
  32331. var xSubRatio = 0;
  32332. var ySubRatio = 0;
  32333. var zSubRatio = 0;
  32334. var subSq = 0;
  32335. if (computeFacetPartitioning && options && options.bbSize) {
  32336. var ox = 0; // X partitioning index for facet position
  32337. var oy = 0; // Y partinioning index for facet position
  32338. var oz = 0; // Z partinioning index for facet position
  32339. var b1x = 0; // X partitioning index for facet v1 vertex
  32340. var b1y = 0; // Y partitioning index for facet v1 vertex
  32341. var b1z = 0; // z partitioning index for facet v1 vertex
  32342. var b2x = 0; // X partitioning index for facet v2 vertex
  32343. var b2y = 0; // Y partitioning index for facet v2 vertex
  32344. var b2z = 0; // Z partitioning index for facet v2 vertex
  32345. var b3x = 0; // X partitioning index for facet v3 vertex
  32346. var b3y = 0; // Y partitioning index for facet v3 vertex
  32347. var b3z = 0; // Z partitioning index for facet v3 vertex
  32348. var block_idx_o = 0; // facet barycenter block index
  32349. var block_idx_v1 = 0; // v1 vertex block index
  32350. var block_idx_v2 = 0; // v2 vertex block index
  32351. var block_idx_v3 = 0; // v3 vertex block index
  32352. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32353. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32354. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32355. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32356. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32357. subSq = options.subDiv.max * options.subDiv.max;
  32358. options.facetPartitioning.length = 0;
  32359. }
  32360. // reset the normals
  32361. for (index = 0; index < positions.length; index++) {
  32362. normals[index] = 0.0;
  32363. }
  32364. // Loop : 1 indice triplet = 1 facet
  32365. var nbFaces = (indices.length / 3) | 0;
  32366. for (index = 0; index < nbFaces; index++) {
  32367. // get the indexes of the coordinates of each vertex of the facet
  32368. v1x = indices[index * 3] * 3;
  32369. v1y = v1x + 1;
  32370. v1z = v1x + 2;
  32371. v2x = indices[index * 3 + 1] * 3;
  32372. v2y = v2x + 1;
  32373. v2z = v2x + 2;
  32374. v3x = indices[index * 3 + 2] * 3;
  32375. v3y = v3x + 1;
  32376. v3z = v3x + 2;
  32377. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32378. p1p2y = positions[v1y] - positions[v2y];
  32379. p1p2z = positions[v1z] - positions[v2z];
  32380. p3p2x = positions[v3x] - positions[v2x];
  32381. p3p2y = positions[v3y] - positions[v2y];
  32382. p3p2z = positions[v3z] - positions[v2z];
  32383. // compute the face normal with the cross product
  32384. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32385. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32386. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32387. // normalize this normal and store it in the array facetData
  32388. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32389. length = (length === 0) ? 1.0 : length;
  32390. faceNormalx /= length;
  32391. faceNormaly /= length;
  32392. faceNormalz /= length;
  32393. if (computeFacetNormals && options) {
  32394. options.facetNormals[index].x = faceNormalx;
  32395. options.facetNormals[index].y = faceNormaly;
  32396. options.facetNormals[index].z = faceNormalz;
  32397. }
  32398. if (computeFacetPositions && options) {
  32399. // compute and the facet barycenter coordinates in the array facetPositions
  32400. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32401. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32402. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32403. }
  32404. if (computeFacetPartitioning && options) {
  32405. // store the facet indexes in arrays in the main facetPartitioning array :
  32406. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32407. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32408. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32409. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32410. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32411. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32412. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32413. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32414. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32415. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32416. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32417. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32418. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32419. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32420. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32421. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32422. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32423. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32424. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32425. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32426. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32427. // push each facet index in each block containing the vertex
  32428. options.facetPartitioning[block_idx_v1].push(index);
  32429. if (block_idx_v2 != block_idx_v1) {
  32430. options.facetPartitioning[block_idx_v2].push(index);
  32431. }
  32432. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32433. options.facetPartitioning[block_idx_v3].push(index);
  32434. }
  32435. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32436. options.facetPartitioning[block_idx_o].push(index);
  32437. }
  32438. }
  32439. if (computeDepthSort && options && options.facetPositions) {
  32440. var dsf = depthSortedFacets[index];
  32441. dsf.ind = index * 3;
  32442. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32443. }
  32444. // compute the normals anyway
  32445. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32446. normals[v1y] += faceNormaly;
  32447. normals[v1z] += faceNormalz;
  32448. normals[v2x] += faceNormalx;
  32449. normals[v2y] += faceNormaly;
  32450. normals[v2z] += faceNormalz;
  32451. normals[v3x] += faceNormalx;
  32452. normals[v3y] += faceNormaly;
  32453. normals[v3z] += faceNormalz;
  32454. }
  32455. // last normalization of each normal
  32456. for (index = 0; index < normals.length / 3; index++) {
  32457. faceNormalx = normals[index * 3];
  32458. faceNormaly = normals[index * 3 + 1];
  32459. faceNormalz = normals[index * 3 + 2];
  32460. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32461. length = (length === 0) ? 1.0 : length;
  32462. faceNormalx /= length;
  32463. faceNormaly /= length;
  32464. faceNormalz /= length;
  32465. normals[index * 3] = faceNormalx;
  32466. normals[index * 3 + 1] = faceNormaly;
  32467. normals[index * 3 + 2] = faceNormalz;
  32468. }
  32469. };
  32470. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32471. var li = indices.length;
  32472. var ln = normals.length;
  32473. var i;
  32474. var n;
  32475. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32476. switch (sideOrientation) {
  32477. case BABYLON.Mesh.FRONTSIDE:
  32478. // nothing changed
  32479. break;
  32480. case BABYLON.Mesh.BACKSIDE:
  32481. var tmp;
  32482. // indices
  32483. for (i = 0; i < li; i += 3) {
  32484. tmp = indices[i];
  32485. indices[i] = indices[i + 2];
  32486. indices[i + 2] = tmp;
  32487. }
  32488. // normals
  32489. for (n = 0; n < ln; n++) {
  32490. normals[n] = -normals[n];
  32491. }
  32492. break;
  32493. case BABYLON.Mesh.DOUBLESIDE:
  32494. // positions
  32495. var lp = positions.length;
  32496. var l = lp / 3;
  32497. for (var p = 0; p < lp; p++) {
  32498. positions[lp + p] = positions[p];
  32499. }
  32500. // indices
  32501. for (i = 0; i < li; i += 3) {
  32502. indices[i + li] = indices[i + 2] + l;
  32503. indices[i + 1 + li] = indices[i + 1] + l;
  32504. indices[i + 2 + li] = indices[i] + l;
  32505. }
  32506. // normals
  32507. for (n = 0; n < ln; n++) {
  32508. normals[ln + n] = -normals[n];
  32509. }
  32510. // uvs
  32511. var lu = uvs.length;
  32512. var u = 0;
  32513. for (u = 0; u < lu; u++) {
  32514. uvs[u + lu] = uvs[u];
  32515. }
  32516. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32517. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32518. u = 0;
  32519. for (i = 0; i < lu / 2; i++) {
  32520. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32521. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32522. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32523. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32524. u += 2;
  32525. }
  32526. break;
  32527. }
  32528. };
  32529. /**
  32530. * Creates a new VertexData from the imported parameters.
  32531. */
  32532. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32533. var vertexData = new VertexData();
  32534. // positions
  32535. var positions = parsedVertexData.positions;
  32536. if (positions) {
  32537. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32538. }
  32539. // normals
  32540. var normals = parsedVertexData.normals;
  32541. if (normals) {
  32542. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32543. }
  32544. // tangents
  32545. var tangents = parsedVertexData.tangents;
  32546. if (tangents) {
  32547. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32548. }
  32549. // uvs
  32550. var uvs = parsedVertexData.uvs;
  32551. if (uvs) {
  32552. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32553. }
  32554. // uv2s
  32555. var uv2s = parsedVertexData.uv2s;
  32556. if (uv2s) {
  32557. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32558. }
  32559. // uv3s
  32560. var uv3s = parsedVertexData.uv3s;
  32561. if (uv3s) {
  32562. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32563. }
  32564. // uv4s
  32565. var uv4s = parsedVertexData.uv4s;
  32566. if (uv4s) {
  32567. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32568. }
  32569. // uv5s
  32570. var uv5s = parsedVertexData.uv5s;
  32571. if (uv5s) {
  32572. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32573. }
  32574. // uv6s
  32575. var uv6s = parsedVertexData.uv6s;
  32576. if (uv6s) {
  32577. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32578. }
  32579. // colors
  32580. var colors = parsedVertexData.colors;
  32581. if (colors) {
  32582. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32583. }
  32584. // matricesIndices
  32585. var matricesIndices = parsedVertexData.matricesIndices;
  32586. if (matricesIndices) {
  32587. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32588. }
  32589. // matricesWeights
  32590. var matricesWeights = parsedVertexData.matricesWeights;
  32591. if (matricesWeights) {
  32592. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32593. }
  32594. // indices
  32595. var indices = parsedVertexData.indices;
  32596. if (indices) {
  32597. vertexData.indices = indices;
  32598. }
  32599. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32600. };
  32601. return VertexData;
  32602. }());
  32603. BABYLON.VertexData = VertexData;
  32604. })(BABYLON || (BABYLON = {}));
  32605. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32606. var BABYLON;
  32607. (function (BABYLON) {
  32608. /**
  32609. * Class used to store geometry data (vertex buffers + index buffer)
  32610. */
  32611. var Geometry = /** @class */ (function () {
  32612. /**
  32613. * Creates a new geometry
  32614. * @param id defines the unique ID
  32615. * @param scene defines the hosting scene
  32616. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32617. * @param updatable defines if geometry must be updatable (false by default)
  32618. * @param mesh defines the mesh that will be associated with the geometry
  32619. */
  32620. function Geometry(id, scene, vertexData, updatable, mesh) {
  32621. if (updatable === void 0) { updatable = false; }
  32622. if (mesh === void 0) { mesh = null; }
  32623. /**
  32624. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32625. */
  32626. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32627. this._totalVertices = 0;
  32628. this._isDisposed = false;
  32629. this._indexBufferIsUpdatable = false;
  32630. this.id = id;
  32631. this._engine = scene.getEngine();
  32632. this._meshes = [];
  32633. this._scene = scene;
  32634. //Init vertex buffer cache
  32635. this._vertexBuffers = {};
  32636. this._indices = [];
  32637. this._updatable = updatable;
  32638. // vertexData
  32639. if (vertexData) {
  32640. this.setAllVerticesData(vertexData, updatable);
  32641. }
  32642. else {
  32643. this._totalVertices = 0;
  32644. this._indices = [];
  32645. }
  32646. if (this._engine.getCaps().vertexArrayObject) {
  32647. this._vertexArrayObjects = {};
  32648. }
  32649. // applyToMesh
  32650. if (mesh) {
  32651. if (mesh.getClassName() === "LinesMesh") {
  32652. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32653. this.updateExtend();
  32654. }
  32655. this.applyToMesh(mesh);
  32656. mesh.computeWorldMatrix(true);
  32657. }
  32658. }
  32659. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32660. /**
  32661. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32662. */
  32663. get: function () {
  32664. return this._boundingBias;
  32665. },
  32666. /**
  32667. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32668. */
  32669. set: function (value) {
  32670. if (this._boundingBias && this._boundingBias.equals(value)) {
  32671. return;
  32672. }
  32673. this._boundingBias = value.clone();
  32674. this.updateBoundingInfo(true, null);
  32675. },
  32676. enumerable: true,
  32677. configurable: true
  32678. });
  32679. /**
  32680. * Static function used to attach a new empty geometry to a mesh
  32681. * @param mesh defines the mesh to attach the geometry to
  32682. * @returns the new {BABYLON.Geometry}
  32683. */
  32684. Geometry.CreateGeometryForMesh = function (mesh) {
  32685. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32686. geometry.applyToMesh(mesh);
  32687. return geometry;
  32688. };
  32689. Object.defineProperty(Geometry.prototype, "extend", {
  32690. /**
  32691. * Gets the current extend of the geometry
  32692. */
  32693. get: function () {
  32694. return this._extend;
  32695. },
  32696. enumerable: true,
  32697. configurable: true
  32698. });
  32699. /**
  32700. * Gets the hosting scene
  32701. * @returns the hosting {BABYLON.Scene}
  32702. */
  32703. Geometry.prototype.getScene = function () {
  32704. return this._scene;
  32705. };
  32706. /**
  32707. * Gets the hosting engine
  32708. * @returns the hosting {BABYLON.Engine}
  32709. */
  32710. Geometry.prototype.getEngine = function () {
  32711. return this._engine;
  32712. };
  32713. /**
  32714. * Defines if the geometry is ready to use
  32715. * @returns true if the geometry is ready to be used
  32716. */
  32717. Geometry.prototype.isReady = function () {
  32718. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32719. };
  32720. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32721. /**
  32722. * Gets a value indicating that the geometry should not be serialized
  32723. */
  32724. get: function () {
  32725. for (var index = 0; index < this._meshes.length; index++) {
  32726. if (!this._meshes[index].doNotSerialize) {
  32727. return false;
  32728. }
  32729. }
  32730. return true;
  32731. },
  32732. enumerable: true,
  32733. configurable: true
  32734. });
  32735. /** @ignore */
  32736. Geometry.prototype._rebuild = function () {
  32737. if (this._vertexArrayObjects) {
  32738. this._vertexArrayObjects = {};
  32739. }
  32740. // Index buffer
  32741. if (this._meshes.length !== 0 && this._indices) {
  32742. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32743. }
  32744. // Vertex buffers
  32745. for (var key in this._vertexBuffers) {
  32746. var vertexBuffer = this._vertexBuffers[key];
  32747. vertexBuffer._rebuild();
  32748. }
  32749. };
  32750. /**
  32751. * Affects all gemetry data in one call
  32752. * @param vertexData defines the geometry data
  32753. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32754. */
  32755. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32756. vertexData.applyToGeometry(this, updatable);
  32757. this.notifyUpdate();
  32758. };
  32759. /**
  32760. * Set specific vertex data
  32761. * @param kind defines the data kind (Position, normal, etc...)
  32762. * @param data defines the vertex data to use
  32763. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32764. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32765. */
  32766. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32767. if (updatable === void 0) { updatable = false; }
  32768. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32769. this.setVerticesBuffer(buffer);
  32770. };
  32771. /**
  32772. * Removes a specific vertex data
  32773. * @param kind defines the data kind (Position, normal, etc...)
  32774. */
  32775. Geometry.prototype.removeVerticesData = function (kind) {
  32776. if (this._vertexBuffers[kind]) {
  32777. this._vertexBuffers[kind].dispose();
  32778. delete this._vertexBuffers[kind];
  32779. }
  32780. };
  32781. /**
  32782. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32783. * @param buffer defines the vertex buffer to use
  32784. */
  32785. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32786. var kind = buffer.getKind();
  32787. if (this._vertexBuffers[kind]) {
  32788. this._vertexBuffers[kind].dispose();
  32789. }
  32790. this._vertexBuffers[kind] = buffer;
  32791. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32792. var data = buffer.getData();
  32793. var stride = buffer.getStrideSize();
  32794. this._totalVertices = data.length / stride;
  32795. this.updateExtend(data, stride);
  32796. this._resetPointsArrayCache();
  32797. var meshes = this._meshes;
  32798. var numOfMeshes = meshes.length;
  32799. for (var index = 0; index < numOfMeshes; index++) {
  32800. var mesh = meshes[index];
  32801. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32802. mesh._createGlobalSubMesh(false);
  32803. mesh.computeWorldMatrix(true);
  32804. }
  32805. }
  32806. this.notifyUpdate(kind);
  32807. if (this._vertexArrayObjects) {
  32808. this._disposeVertexArrayObjects();
  32809. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32810. }
  32811. };
  32812. /**
  32813. * Update a specific vertex buffer
  32814. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32815. * It will do nothing if the buffer is not updatable
  32816. * @param kind defines the data kind (Position, normal, etc...)
  32817. * @param data defines the data to use
  32818. * @param offset defines the offset in the target buffer where to store the data
  32819. */
  32820. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32821. var vertexBuffer = this.getVertexBuffer(kind);
  32822. if (!vertexBuffer) {
  32823. return;
  32824. }
  32825. vertexBuffer.updateDirectly(data, offset);
  32826. this.notifyUpdate(kind);
  32827. };
  32828. /**
  32829. * Update a specific vertex buffer
  32830. * This function will create a new buffer if the current one is not updatable
  32831. * @param kind defines the data kind (Position, normal, etc...)
  32832. * @param data defines the data to use
  32833. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32834. */
  32835. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32836. if (updateExtends === void 0) { updateExtends = false; }
  32837. var vertexBuffer = this.getVertexBuffer(kind);
  32838. if (!vertexBuffer) {
  32839. return;
  32840. }
  32841. vertexBuffer.update(data);
  32842. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32843. var stride = vertexBuffer.getStrideSize();
  32844. this._totalVertices = data.length / stride;
  32845. this.updateBoundingInfo(updateExtends, data);
  32846. }
  32847. this.notifyUpdate(kind);
  32848. };
  32849. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32850. if (updateExtends) {
  32851. this.updateExtend(data);
  32852. }
  32853. var meshes = this._meshes;
  32854. var numOfMeshes = meshes.length;
  32855. this._resetPointsArrayCache();
  32856. for (var index = 0; index < numOfMeshes; index++) {
  32857. var mesh = meshes[index];
  32858. if (updateExtends) {
  32859. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32860. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32861. var subMesh = mesh.subMeshes[subIndex];
  32862. subMesh.refreshBoundingInfo();
  32863. }
  32864. }
  32865. }
  32866. };
  32867. /** @ignore */
  32868. Geometry.prototype._bind = function (effect, indexToBind) {
  32869. if (!effect) {
  32870. return;
  32871. }
  32872. if (indexToBind === undefined) {
  32873. indexToBind = this._indexBuffer;
  32874. }
  32875. var vbs = this.getVertexBuffers();
  32876. if (!vbs) {
  32877. return;
  32878. }
  32879. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32880. this._engine.bindBuffers(vbs, indexToBind, effect);
  32881. return;
  32882. }
  32883. // Using VAO
  32884. if (!this._vertexArrayObjects[effect.key]) {
  32885. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32886. }
  32887. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32888. };
  32889. /**
  32890. * Gets total number of vertices
  32891. * @returns the total number of vertices
  32892. */
  32893. Geometry.prototype.getTotalVertices = function () {
  32894. if (!this.isReady()) {
  32895. return 0;
  32896. }
  32897. return this._totalVertices;
  32898. };
  32899. /**
  32900. * Gets a specific vertex data attached to this geometry
  32901. * @param kind defines the data kind (Position, normal, etc...)
  32902. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32903. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32904. * @returns a float array containing vertex data
  32905. */
  32906. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32907. var vertexBuffer = this.getVertexBuffer(kind);
  32908. if (!vertexBuffer) {
  32909. return null;
  32910. }
  32911. var orig = vertexBuffer.getData();
  32912. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32913. return orig;
  32914. }
  32915. else {
  32916. var len = orig.length;
  32917. var copy = [];
  32918. for (var i = 0; i < len; i++) {
  32919. copy.push(orig[i]);
  32920. }
  32921. return copy;
  32922. }
  32923. };
  32924. /**
  32925. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32926. * @param kind defines the data kind (Position, normal, etc...)
  32927. * @returns true if the vertex buffer with the specified kind is updatable
  32928. */
  32929. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32930. var vb = this._vertexBuffers[kind];
  32931. if (!vb) {
  32932. return false;
  32933. }
  32934. return vb.isUpdatable();
  32935. };
  32936. /**
  32937. * Gets a specific vertex buffer
  32938. * @param kind defines the data kind (Position, normal, etc...)
  32939. * @returns a {BABYLON.VertexBuffer}
  32940. */
  32941. Geometry.prototype.getVertexBuffer = function (kind) {
  32942. if (!this.isReady()) {
  32943. return null;
  32944. }
  32945. return this._vertexBuffers[kind];
  32946. };
  32947. /**
  32948. * Returns all vertex buffers
  32949. * @return an object holding all vertex buffers indexed by kind
  32950. */
  32951. Geometry.prototype.getVertexBuffers = function () {
  32952. if (!this.isReady()) {
  32953. return null;
  32954. }
  32955. return this._vertexBuffers;
  32956. };
  32957. /**
  32958. * Gets a boolean indicating if specific vertex buffer is present
  32959. * @param kind defines the data kind (Position, normal, etc...)
  32960. * @returns true if data is present
  32961. */
  32962. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32963. if (!this._vertexBuffers) {
  32964. if (this._delayInfo) {
  32965. return this._delayInfo.indexOf(kind) !== -1;
  32966. }
  32967. return false;
  32968. }
  32969. return this._vertexBuffers[kind] !== undefined;
  32970. };
  32971. /**
  32972. * Gets a list of all attached data kinds (Position, normal, etc...)
  32973. * @returns a list of string containing all kinds
  32974. */
  32975. Geometry.prototype.getVerticesDataKinds = function () {
  32976. var result = [];
  32977. var kind;
  32978. if (!this._vertexBuffers && this._delayInfo) {
  32979. for (kind in this._delayInfo) {
  32980. result.push(kind);
  32981. }
  32982. }
  32983. else {
  32984. for (kind in this._vertexBuffers) {
  32985. result.push(kind);
  32986. }
  32987. }
  32988. return result;
  32989. };
  32990. /**
  32991. * Update index buffer
  32992. * @param indices defines the indices to store in the index buffer
  32993. * @param offset defines the offset in the target buffer where to store the data
  32994. */
  32995. Geometry.prototype.updateIndices = function (indices, offset) {
  32996. if (!this._indexBuffer) {
  32997. return;
  32998. }
  32999. if (!this._indexBufferIsUpdatable) {
  33000. this.setIndices(indices, null, true);
  33001. }
  33002. else {
  33003. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  33004. }
  33005. };
  33006. /**
  33007. * Creates a new index buffer
  33008. * @param indices defines the indices to store in the index buffer
  33009. * @param totalVertices defines the total number of vertices (could be null)
  33010. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  33011. */
  33012. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  33013. if (totalVertices === void 0) { totalVertices = null; }
  33014. if (updatable === void 0) { updatable = false; }
  33015. if (this._indexBuffer) {
  33016. this._engine._releaseBuffer(this._indexBuffer);
  33017. }
  33018. this._disposeVertexArrayObjects();
  33019. this._indices = indices;
  33020. this._indexBufferIsUpdatable = updatable;
  33021. if (this._meshes.length !== 0 && this._indices) {
  33022. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  33023. }
  33024. if (totalVertices != undefined) {
  33025. this._totalVertices = totalVertices;
  33026. }
  33027. var meshes = this._meshes;
  33028. var numOfMeshes = meshes.length;
  33029. for (var index = 0; index < numOfMeshes; index++) {
  33030. meshes[index]._createGlobalSubMesh(true);
  33031. }
  33032. this.notifyUpdate();
  33033. };
  33034. /**
  33035. * Return the total number of indices
  33036. * @returns the total number of indices
  33037. */
  33038. Geometry.prototype.getTotalIndices = function () {
  33039. if (!this.isReady()) {
  33040. return 0;
  33041. }
  33042. return this._indices.length;
  33043. };
  33044. /**
  33045. * Gets the index buffer array
  33046. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33047. * @returns the index buffer array
  33048. */
  33049. Geometry.prototype.getIndices = function (copyWhenShared) {
  33050. if (!this.isReady()) {
  33051. return null;
  33052. }
  33053. var orig = this._indices;
  33054. if (!copyWhenShared || this._meshes.length === 1) {
  33055. return orig;
  33056. }
  33057. else {
  33058. var len = orig.length;
  33059. var copy = [];
  33060. for (var i = 0; i < len; i++) {
  33061. copy.push(orig[i]);
  33062. }
  33063. return copy;
  33064. }
  33065. };
  33066. /**
  33067. * Gets the index buffer
  33068. * @return the index buffer
  33069. */
  33070. Geometry.prototype.getIndexBuffer = function () {
  33071. if (!this.isReady()) {
  33072. return null;
  33073. }
  33074. return this._indexBuffer;
  33075. };
  33076. /** @ignore */
  33077. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  33078. if (effect === void 0) { effect = null; }
  33079. if (!effect || !this._vertexArrayObjects) {
  33080. return;
  33081. }
  33082. if (this._vertexArrayObjects[effect.key]) {
  33083. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  33084. delete this._vertexArrayObjects[effect.key];
  33085. }
  33086. };
  33087. /**
  33088. * Release the associated resources for a specific mesh
  33089. * @param mesh defines the source mesh
  33090. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  33091. */
  33092. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33093. var meshes = this._meshes;
  33094. var index = meshes.indexOf(mesh);
  33095. if (index === -1) {
  33096. return;
  33097. }
  33098. meshes.splice(index, 1);
  33099. mesh._geometry = null;
  33100. if (meshes.length === 0 && shouldDispose) {
  33101. this.dispose();
  33102. }
  33103. };
  33104. /**
  33105. * Apply current geometry to a given mesh
  33106. * @param mesh defines the mesh to apply geometry to
  33107. */
  33108. Geometry.prototype.applyToMesh = function (mesh) {
  33109. if (mesh._geometry === this) {
  33110. return;
  33111. }
  33112. var previousGeometry = mesh._geometry;
  33113. if (previousGeometry) {
  33114. previousGeometry.releaseForMesh(mesh);
  33115. }
  33116. var meshes = this._meshes;
  33117. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33118. mesh._geometry = this;
  33119. this._scene.pushGeometry(this);
  33120. meshes.push(mesh);
  33121. if (this.isReady()) {
  33122. this._applyToMesh(mesh);
  33123. }
  33124. else {
  33125. mesh._boundingInfo = this._boundingInfo;
  33126. }
  33127. };
  33128. Geometry.prototype.updateExtend = function (data, stride) {
  33129. if (data === void 0) { data = null; }
  33130. if (!data) {
  33131. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33132. }
  33133. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33134. };
  33135. Geometry.prototype._applyToMesh = function (mesh) {
  33136. var numOfMeshes = this._meshes.length;
  33137. // vertexBuffers
  33138. for (var kind in this._vertexBuffers) {
  33139. if (numOfMeshes === 1) {
  33140. this._vertexBuffers[kind].create();
  33141. }
  33142. var buffer = this._vertexBuffers[kind].getBuffer();
  33143. if (buffer)
  33144. buffer.references = numOfMeshes;
  33145. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33146. if (!this._extend) {
  33147. this.updateExtend(this._vertexBuffers[kind].getData());
  33148. }
  33149. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33150. mesh._createGlobalSubMesh(false);
  33151. //bounding info was just created again, world matrix should be applied again.
  33152. mesh._updateBoundingInfo();
  33153. }
  33154. }
  33155. // indexBuffer
  33156. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33157. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33158. }
  33159. if (this._indexBuffer) {
  33160. this._indexBuffer.references = numOfMeshes;
  33161. }
  33162. };
  33163. Geometry.prototype.notifyUpdate = function (kind) {
  33164. if (this.onGeometryUpdated) {
  33165. this.onGeometryUpdated(this, kind);
  33166. }
  33167. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33168. var mesh = _a[_i];
  33169. mesh._markSubMeshesAsAttributesDirty();
  33170. }
  33171. };
  33172. /**
  33173. * Load the geometry if it was flagged as delay loaded
  33174. * @param scene defines the hosting scene
  33175. * @param onLoaded defines a callback called when the geometry is loaded
  33176. */
  33177. Geometry.prototype.load = function (scene, onLoaded) {
  33178. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33179. return;
  33180. }
  33181. if (this.isReady()) {
  33182. if (onLoaded) {
  33183. onLoaded();
  33184. }
  33185. return;
  33186. }
  33187. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33188. this._queueLoad(scene, onLoaded);
  33189. };
  33190. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33191. var _this = this;
  33192. if (!this.delayLoadingFile) {
  33193. return;
  33194. }
  33195. scene._addPendingData(this);
  33196. scene._loadFile(this.delayLoadingFile, function (data) {
  33197. if (!_this._delayLoadingFunction) {
  33198. return;
  33199. }
  33200. _this._delayLoadingFunction(JSON.parse(data), _this);
  33201. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33202. _this._delayInfo = [];
  33203. scene._removePendingData(_this);
  33204. var meshes = _this._meshes;
  33205. var numOfMeshes = meshes.length;
  33206. for (var index = 0; index < numOfMeshes; index++) {
  33207. _this._applyToMesh(meshes[index]);
  33208. }
  33209. if (onLoaded) {
  33210. onLoaded();
  33211. }
  33212. }, undefined, true);
  33213. };
  33214. /**
  33215. * Invert the geometry to move from a right handed system to a left handed one.
  33216. */
  33217. Geometry.prototype.toLeftHanded = function () {
  33218. // Flip faces
  33219. var tIndices = this.getIndices(false);
  33220. if (tIndices != null && tIndices.length > 0) {
  33221. for (var i = 0; i < tIndices.length; i += 3) {
  33222. var tTemp = tIndices[i + 0];
  33223. tIndices[i + 0] = tIndices[i + 2];
  33224. tIndices[i + 2] = tTemp;
  33225. }
  33226. this.setIndices(tIndices);
  33227. }
  33228. // Negate position.z
  33229. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33230. if (tPositions != null && tPositions.length > 0) {
  33231. for (var i = 0; i < tPositions.length; i += 3) {
  33232. tPositions[i + 2] = -tPositions[i + 2];
  33233. }
  33234. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33235. }
  33236. // Negate normal.z
  33237. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33238. if (tNormals != null && tNormals.length > 0) {
  33239. for (var i = 0; i < tNormals.length; i += 3) {
  33240. tNormals[i + 2] = -tNormals[i + 2];
  33241. }
  33242. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33243. }
  33244. };
  33245. // Cache
  33246. /** @ignore */
  33247. Geometry.prototype._resetPointsArrayCache = function () {
  33248. this._positions = null;
  33249. };
  33250. /** @ignore */
  33251. Geometry.prototype._generatePointsArray = function () {
  33252. if (this._positions)
  33253. return true;
  33254. this._positions = [];
  33255. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33256. if (!data) {
  33257. return false;
  33258. }
  33259. for (var index = 0; index < data.length; index += 3) {
  33260. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33261. }
  33262. return true;
  33263. };
  33264. /**
  33265. * Gets a value indicating if the geometry is disposed
  33266. * @returns true if the geometry was disposed
  33267. */
  33268. Geometry.prototype.isDisposed = function () {
  33269. return this._isDisposed;
  33270. };
  33271. Geometry.prototype._disposeVertexArrayObjects = function () {
  33272. if (this._vertexArrayObjects) {
  33273. for (var kind in this._vertexArrayObjects) {
  33274. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33275. }
  33276. this._vertexArrayObjects = {};
  33277. }
  33278. };
  33279. /**
  33280. * Free all associated resources
  33281. */
  33282. Geometry.prototype.dispose = function () {
  33283. var meshes = this._meshes;
  33284. var numOfMeshes = meshes.length;
  33285. var index;
  33286. for (index = 0; index < numOfMeshes; index++) {
  33287. this.releaseForMesh(meshes[index]);
  33288. }
  33289. this._meshes = [];
  33290. this._disposeVertexArrayObjects();
  33291. for (var kind in this._vertexBuffers) {
  33292. this._vertexBuffers[kind].dispose();
  33293. }
  33294. this._vertexBuffers = {};
  33295. this._totalVertices = 0;
  33296. if (this._indexBuffer) {
  33297. this._engine._releaseBuffer(this._indexBuffer);
  33298. }
  33299. this._indexBuffer = null;
  33300. this._indices = [];
  33301. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33302. this.delayLoadingFile = null;
  33303. this._delayLoadingFunction = null;
  33304. this._delayInfo = [];
  33305. this._boundingInfo = null;
  33306. this._scene.removeGeometry(this);
  33307. this._isDisposed = true;
  33308. };
  33309. /**
  33310. * Clone the current geometry into a new geometry
  33311. * @param id defines the unique ID of the new geometry
  33312. * @returns a new geometry object
  33313. */
  33314. Geometry.prototype.copy = function (id) {
  33315. var vertexData = new BABYLON.VertexData();
  33316. vertexData.indices = [];
  33317. var indices = this.getIndices();
  33318. if (indices) {
  33319. for (var index = 0; index < indices.length; index++) {
  33320. vertexData.indices.push(indices[index]);
  33321. }
  33322. }
  33323. var updatable = false;
  33324. var stopChecking = false;
  33325. var kind;
  33326. for (kind in this._vertexBuffers) {
  33327. // using slice() to make a copy of the array and not just reference it
  33328. var data = this.getVerticesData(kind);
  33329. if (data instanceof Float32Array) {
  33330. vertexData.set(new Float32Array(data), kind);
  33331. }
  33332. else {
  33333. vertexData.set(data.slice(0), kind);
  33334. }
  33335. if (!stopChecking) {
  33336. var vb = this.getVertexBuffer(kind);
  33337. if (vb) {
  33338. updatable = vb.isUpdatable();
  33339. stopChecking = !updatable;
  33340. }
  33341. }
  33342. }
  33343. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33344. geometry.delayLoadState = this.delayLoadState;
  33345. geometry.delayLoadingFile = this.delayLoadingFile;
  33346. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33347. for (kind in this._delayInfo) {
  33348. geometry._delayInfo = geometry._delayInfo || [];
  33349. geometry._delayInfo.push(kind);
  33350. }
  33351. // Bounding info
  33352. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33353. return geometry;
  33354. };
  33355. /**
  33356. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33357. * @return a JSON representation of the current geometry data (without the vertices data)
  33358. */
  33359. Geometry.prototype.serialize = function () {
  33360. var serializationObject = {};
  33361. serializationObject.id = this.id;
  33362. serializationObject.updatable = this._updatable;
  33363. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33364. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33365. }
  33366. return serializationObject;
  33367. };
  33368. Geometry.prototype.toNumberArray = function (origin) {
  33369. if (Array.isArray(origin)) {
  33370. return origin;
  33371. }
  33372. else {
  33373. return Array.prototype.slice.call(origin);
  33374. }
  33375. };
  33376. /**
  33377. * Serialize all vertices data into a JSON oject
  33378. * @returns a JSON representation of the current geometry data
  33379. */
  33380. Geometry.prototype.serializeVerticeData = function () {
  33381. var serializationObject = this.serialize();
  33382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33383. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33384. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33385. serializationObject.positions._updatable = true;
  33386. }
  33387. }
  33388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33389. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33391. serializationObject.normals._updatable = true;
  33392. }
  33393. }
  33394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33395. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33397. serializationObject.tangets._updatable = true;
  33398. }
  33399. }
  33400. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33401. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33402. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33403. serializationObject.uvs._updatable = true;
  33404. }
  33405. }
  33406. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33407. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33408. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33409. serializationObject.uv2s._updatable = true;
  33410. }
  33411. }
  33412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33413. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33414. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33415. serializationObject.uv3s._updatable = true;
  33416. }
  33417. }
  33418. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33419. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33420. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33421. serializationObject.uv4s._updatable = true;
  33422. }
  33423. }
  33424. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33425. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33426. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33427. serializationObject.uv5s._updatable = true;
  33428. }
  33429. }
  33430. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33431. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33432. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33433. serializationObject.uv6s._updatable = true;
  33434. }
  33435. }
  33436. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33437. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33438. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33439. serializationObject.colors._updatable = true;
  33440. }
  33441. }
  33442. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33443. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33444. serializationObject.matricesIndices._isExpanded = true;
  33445. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33446. serializationObject.matricesIndices._updatable = true;
  33447. }
  33448. }
  33449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33450. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33451. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33452. serializationObject.matricesWeights._updatable = true;
  33453. }
  33454. }
  33455. serializationObject.indices = this.toNumberArray(this.getIndices());
  33456. return serializationObject;
  33457. };
  33458. // Statics
  33459. /**
  33460. * Extracts a clone of a mesh geometry
  33461. * @param mesh defines the source mesh
  33462. * @param id defines the unique ID of the new geometry object
  33463. * @returns the new geometry object
  33464. */
  33465. Geometry.ExtractFromMesh = function (mesh, id) {
  33466. var geometry = mesh._geometry;
  33467. if (!geometry) {
  33468. return null;
  33469. }
  33470. return geometry.copy(id);
  33471. };
  33472. /**
  33473. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33474. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33475. * Be aware Math.random() could cause collisions, but:
  33476. * "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"
  33477. * @returns a string containing a new GUID
  33478. */
  33479. Geometry.RandomId = function () {
  33480. return BABYLON.Tools.RandomId();
  33481. };
  33482. /** @ignore */
  33483. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33484. var scene = mesh.getScene();
  33485. // Geometry
  33486. var geometryId = parsedGeometry.geometryId;
  33487. if (geometryId) {
  33488. var geometry = scene.getGeometryByID(geometryId);
  33489. if (geometry) {
  33490. geometry.applyToMesh(mesh);
  33491. }
  33492. }
  33493. else if (parsedGeometry instanceof ArrayBuffer) {
  33494. var binaryInfo = mesh._binaryInfo;
  33495. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33496. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33497. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33498. }
  33499. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33500. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33501. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33502. }
  33503. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33504. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33505. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33506. }
  33507. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33508. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33509. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33510. }
  33511. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33512. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33513. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33514. }
  33515. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33516. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33517. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33518. }
  33519. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33520. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33521. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33522. }
  33523. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33524. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33525. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33526. }
  33527. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33528. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33529. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33530. }
  33531. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33532. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33533. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33534. }
  33535. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33536. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33537. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33538. }
  33539. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33540. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33541. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33542. }
  33543. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33544. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33545. mesh.setIndices(indicesData, null);
  33546. }
  33547. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33548. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33549. mesh.subMeshes = [];
  33550. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33551. var materialIndex = subMeshesData[(i * 5) + 0];
  33552. var verticesStart = subMeshesData[(i * 5) + 1];
  33553. var verticesCount = subMeshesData[(i * 5) + 2];
  33554. var indexStart = subMeshesData[(i * 5) + 3];
  33555. var indexCount = subMeshesData[(i * 5) + 4];
  33556. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33557. }
  33558. }
  33559. }
  33560. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33561. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33562. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33563. if (parsedGeometry.tangents) {
  33564. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33565. }
  33566. if (parsedGeometry.uvs) {
  33567. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33568. }
  33569. if (parsedGeometry.uvs2) {
  33570. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33571. }
  33572. if (parsedGeometry.uvs3) {
  33573. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33574. }
  33575. if (parsedGeometry.uvs4) {
  33576. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33577. }
  33578. if (parsedGeometry.uvs5) {
  33579. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33580. }
  33581. if (parsedGeometry.uvs6) {
  33582. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33583. }
  33584. if (parsedGeometry.colors) {
  33585. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33586. }
  33587. if (parsedGeometry.matricesIndices) {
  33588. if (!parsedGeometry.matricesIndices._isExpanded) {
  33589. var floatIndices = [];
  33590. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33591. var matricesIndex = parsedGeometry.matricesIndices[i];
  33592. floatIndices.push(matricesIndex & 0x000000FF);
  33593. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33594. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33595. floatIndices.push(matricesIndex >> 24);
  33596. }
  33597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33598. }
  33599. else {
  33600. delete parsedGeometry.matricesIndices._isExpanded;
  33601. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33602. }
  33603. }
  33604. if (parsedGeometry.matricesIndicesExtra) {
  33605. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33606. var floatIndices = [];
  33607. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33608. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33609. floatIndices.push(matricesIndex & 0x000000FF);
  33610. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33611. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33612. floatIndices.push(matricesIndex >> 24);
  33613. }
  33614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33615. }
  33616. else {
  33617. delete parsedGeometry.matricesIndices._isExpanded;
  33618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33619. }
  33620. }
  33621. if (parsedGeometry.matricesWeights) {
  33622. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33623. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33624. }
  33625. if (parsedGeometry.matricesWeightsExtra) {
  33626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33627. }
  33628. mesh.setIndices(parsedGeometry.indices, null);
  33629. }
  33630. // SubMeshes
  33631. if (parsedGeometry.subMeshes) {
  33632. mesh.subMeshes = [];
  33633. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33634. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33635. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33636. }
  33637. }
  33638. // Flat shading
  33639. if (mesh._shouldGenerateFlatShading) {
  33640. mesh.convertToFlatShadedMesh();
  33641. delete mesh._shouldGenerateFlatShading;
  33642. }
  33643. // Update
  33644. mesh.computeWorldMatrix(true);
  33645. // Octree
  33646. var sceneOctree = scene.selectionOctree;
  33647. if (sceneOctree !== undefined && sceneOctree !== null) {
  33648. sceneOctree.addMesh(mesh);
  33649. }
  33650. };
  33651. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33652. var epsilon = 1e-3;
  33653. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33654. return;
  33655. }
  33656. var noInfluenceBoneIndex = 0.0;
  33657. if (parsedGeometry.skeletonId > -1) {
  33658. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33659. if (!skeleton) {
  33660. return;
  33661. }
  33662. noInfluenceBoneIndex = skeleton.bones.length;
  33663. }
  33664. else {
  33665. return;
  33666. }
  33667. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33668. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33669. var matricesWeights = parsedGeometry.matricesWeights;
  33670. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33671. var influencers = parsedGeometry.numBoneInfluencer;
  33672. var size = matricesWeights.length;
  33673. for (var i = 0; i < size; i += 4) {
  33674. var weight = 0.0;
  33675. var firstZeroWeight = -1;
  33676. for (var j = 0; j < 4; j++) {
  33677. var w = matricesWeights[i + j];
  33678. weight += w;
  33679. if (w < epsilon && firstZeroWeight < 0) {
  33680. firstZeroWeight = j;
  33681. }
  33682. }
  33683. if (matricesWeightsExtra) {
  33684. for (var j = 0; j < 4; j++) {
  33685. var w = matricesWeightsExtra[i + j];
  33686. weight += w;
  33687. if (w < epsilon && firstZeroWeight < 0) {
  33688. firstZeroWeight = j + 4;
  33689. }
  33690. }
  33691. }
  33692. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33693. firstZeroWeight = influencers - 1;
  33694. }
  33695. if (weight > epsilon) {
  33696. var mweight = 1.0 / weight;
  33697. for (var j = 0; j < 4; j++) {
  33698. matricesWeights[i + j] *= mweight;
  33699. }
  33700. if (matricesWeightsExtra) {
  33701. for (var j = 0; j < 4; j++) {
  33702. matricesWeightsExtra[i + j] *= mweight;
  33703. }
  33704. }
  33705. }
  33706. else {
  33707. if (firstZeroWeight >= 4) {
  33708. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33709. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33710. }
  33711. else {
  33712. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33713. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33714. }
  33715. }
  33716. }
  33717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33718. if (parsedGeometry.matricesWeightsExtra) {
  33719. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33720. }
  33721. };
  33722. /**
  33723. * Create a new geometry from persisted data (Using .babylon file format)
  33724. * @param parsedVertexData defines the persisted data
  33725. * @param scene defines the hosting scene
  33726. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33727. * @returns the new geometry object
  33728. */
  33729. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33730. if (scene.getGeometryByID(parsedVertexData.id)) {
  33731. return null; // null since geometry could be something else than a box...
  33732. }
  33733. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33734. if (BABYLON.Tags) {
  33735. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33736. }
  33737. if (parsedVertexData.delayLoadingFile) {
  33738. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33739. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33740. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33741. geometry._delayInfo = [];
  33742. if (parsedVertexData.hasUVs) {
  33743. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33744. }
  33745. if (parsedVertexData.hasUVs2) {
  33746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33747. }
  33748. if (parsedVertexData.hasUVs3) {
  33749. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33750. }
  33751. if (parsedVertexData.hasUVs4) {
  33752. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33753. }
  33754. if (parsedVertexData.hasUVs5) {
  33755. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33756. }
  33757. if (parsedVertexData.hasUVs6) {
  33758. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33759. }
  33760. if (parsedVertexData.hasColors) {
  33761. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33762. }
  33763. if (parsedVertexData.hasMatricesIndices) {
  33764. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33765. }
  33766. if (parsedVertexData.hasMatricesWeights) {
  33767. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33768. }
  33769. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33770. }
  33771. else {
  33772. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33773. }
  33774. scene.pushGeometry(geometry, true);
  33775. return geometry;
  33776. };
  33777. return Geometry;
  33778. }());
  33779. BABYLON.Geometry = Geometry;
  33780. // Primitives
  33781. /// Abstract class
  33782. /**
  33783. * Abstract class used to provide common services for all typed geometries
  33784. */
  33785. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33786. __extends(_PrimitiveGeometry, _super);
  33787. /**
  33788. * Creates a new typed geometry
  33789. * @param id defines the unique ID of the geometry
  33790. * @param scene defines the hosting scene
  33791. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33792. * @param mesh defines the hosting mesh (can be null)
  33793. */
  33794. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33795. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33796. if (mesh === void 0) { mesh = null; }
  33797. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33798. _this._canBeRegenerated = _canBeRegenerated;
  33799. _this._beingRegenerated = true;
  33800. _this.regenerate();
  33801. _this._beingRegenerated = false;
  33802. return _this;
  33803. }
  33804. /**
  33805. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33806. * @returns true if the geometry can be regenerated
  33807. */
  33808. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33809. return this._canBeRegenerated;
  33810. };
  33811. /**
  33812. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33813. */
  33814. _PrimitiveGeometry.prototype.regenerate = function () {
  33815. if (!this._canBeRegenerated) {
  33816. return;
  33817. }
  33818. this._beingRegenerated = true;
  33819. this.setAllVerticesData(this._regenerateVertexData(), false);
  33820. this._beingRegenerated = false;
  33821. };
  33822. /**
  33823. * Clone the geometry
  33824. * @param id defines the unique ID of the new geometry
  33825. * @returns the new geometry
  33826. */
  33827. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33828. return _super.prototype.copy.call(this, id);
  33829. };
  33830. // overrides
  33831. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33832. if (!this._beingRegenerated) {
  33833. return;
  33834. }
  33835. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33836. };
  33837. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33838. if (!this._beingRegenerated) {
  33839. return;
  33840. }
  33841. _super.prototype.setVerticesData.call(this, kind, data, false);
  33842. };
  33843. // to override
  33844. /** @ignore */
  33845. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33846. throw new Error("Abstract method");
  33847. };
  33848. _PrimitiveGeometry.prototype.copy = function (id) {
  33849. throw new Error("Must be overriden in sub-classes.");
  33850. };
  33851. _PrimitiveGeometry.prototype.serialize = function () {
  33852. var serializationObject = _super.prototype.serialize.call(this);
  33853. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33854. return serializationObject;
  33855. };
  33856. return _PrimitiveGeometry;
  33857. }(Geometry));
  33858. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33859. /**
  33860. * Creates a ribbon geometry
  33861. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33862. */
  33863. var RibbonGeometry = /** @class */ (function (_super) {
  33864. __extends(RibbonGeometry, _super);
  33865. /**
  33866. * Creates a ribbon geometry
  33867. * @param id defines the unique ID of the geometry
  33868. * @param scene defines the hosting scene
  33869. * @param pathArray defines the array of paths to use
  33870. * @param closeArray defines if the last path and the first path must be joined
  33871. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33872. * @param offset defines the offset between points
  33873. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33874. * @param mesh defines the hosting mesh (can be null)
  33875. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33876. */
  33877. function RibbonGeometry(id, scene,
  33878. /**
  33879. * Defines the array of paths to use
  33880. */
  33881. pathArray,
  33882. /**
  33883. * Defines if the last and first points of each path in your pathArray must be joined
  33884. */
  33885. closeArray,
  33886. /**
  33887. * Defines if the last and first points of each path in your pathArray must be joined
  33888. */
  33889. closePath,
  33890. /**
  33891. * Defines the offset between points
  33892. */
  33893. offset, canBeRegenerated, mesh,
  33894. /**
  33895. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33896. */
  33897. side) {
  33898. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33899. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33900. _this.pathArray = pathArray;
  33901. _this.closeArray = closeArray;
  33902. _this.closePath = closePath;
  33903. _this.offset = offset;
  33904. _this.side = side;
  33905. return _this;
  33906. }
  33907. /** @ignore */
  33908. RibbonGeometry.prototype._regenerateVertexData = function () {
  33909. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33910. };
  33911. RibbonGeometry.prototype.copy = function (id) {
  33912. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33913. };
  33914. return RibbonGeometry;
  33915. }(_PrimitiveGeometry));
  33916. BABYLON.RibbonGeometry = RibbonGeometry;
  33917. /**
  33918. * Creates a box geometry
  33919. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33920. */
  33921. var BoxGeometry = /** @class */ (function (_super) {
  33922. __extends(BoxGeometry, _super);
  33923. /**
  33924. * Creates a box geometry
  33925. * @param id defines the unique ID of the geometry
  33926. * @param scene defines the hosting scene
  33927. * @param size defines the zise of the box (width, height and depth are the same)
  33928. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33929. * @param mesh defines the hosting mesh (can be null)
  33930. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33931. */
  33932. function BoxGeometry(id, scene,
  33933. /**
  33934. * Defines the zise of the box (width, height and depth are the same)
  33935. */
  33936. size, canBeRegenerated, mesh,
  33937. /**
  33938. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33939. */
  33940. side) {
  33941. if (mesh === void 0) { mesh = null; }
  33942. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33943. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33944. _this.size = size;
  33945. _this.side = side;
  33946. return _this;
  33947. }
  33948. BoxGeometry.prototype._regenerateVertexData = function () {
  33949. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33950. };
  33951. BoxGeometry.prototype.copy = function (id) {
  33952. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33953. };
  33954. BoxGeometry.prototype.serialize = function () {
  33955. var serializationObject = _super.prototype.serialize.call(this);
  33956. serializationObject.size = this.size;
  33957. return serializationObject;
  33958. };
  33959. BoxGeometry.Parse = function (parsedBox, scene) {
  33960. if (scene.getGeometryByID(parsedBox.id)) {
  33961. return null; // null since geometry could be something else than a box...
  33962. }
  33963. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33964. if (BABYLON.Tags) {
  33965. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33966. }
  33967. scene.pushGeometry(box, true);
  33968. return box;
  33969. };
  33970. return BoxGeometry;
  33971. }(_PrimitiveGeometry));
  33972. BABYLON.BoxGeometry = BoxGeometry;
  33973. /**
  33974. * Creates a sphere geometry
  33975. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33976. */
  33977. var SphereGeometry = /** @class */ (function (_super) {
  33978. __extends(SphereGeometry, _super);
  33979. /**
  33980. * Create a new sphere geometry
  33981. * @param id defines the unique ID of the geometry
  33982. * @param scene defines the hosting scene
  33983. * @param segments defines the number of segments to use to create the sphere
  33984. * @param diameter defines the diameter of the sphere
  33985. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33986. * @param mesh defines the hosting mesh (can be null)
  33987. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33988. */
  33989. function SphereGeometry(id, scene,
  33990. /**
  33991. * Defines the number of segments to use to create the sphere
  33992. */
  33993. segments,
  33994. /**
  33995. * Defines the diameter of the sphere
  33996. */
  33997. diameter, canBeRegenerated, mesh,
  33998. /**
  33999. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34000. */
  34001. side) {
  34002. if (mesh === void 0) { mesh = null; }
  34003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34005. _this.segments = segments;
  34006. _this.diameter = diameter;
  34007. _this.side = side;
  34008. return _this;
  34009. }
  34010. SphereGeometry.prototype._regenerateVertexData = function () {
  34011. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34012. };
  34013. SphereGeometry.prototype.copy = function (id) {
  34014. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34015. };
  34016. SphereGeometry.prototype.serialize = function () {
  34017. var serializationObject = _super.prototype.serialize.call(this);
  34018. serializationObject.segments = this.segments;
  34019. serializationObject.diameter = this.diameter;
  34020. return serializationObject;
  34021. };
  34022. SphereGeometry.Parse = function (parsedSphere, scene) {
  34023. if (scene.getGeometryByID(parsedSphere.id)) {
  34024. return null; // null since geometry could be something else than a sphere...
  34025. }
  34026. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34027. if (BABYLON.Tags) {
  34028. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34029. }
  34030. scene.pushGeometry(sphere, true);
  34031. return sphere;
  34032. };
  34033. return SphereGeometry;
  34034. }(_PrimitiveGeometry));
  34035. BABYLON.SphereGeometry = SphereGeometry;
  34036. /**
  34037. * Creates a disc geometry
  34038. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  34039. */
  34040. var DiscGeometry = /** @class */ (function (_super) {
  34041. __extends(DiscGeometry, _super);
  34042. /**
  34043. * Creates a new disc geometry
  34044. * @param id defines the unique ID of the geometry
  34045. * @param scene defines the hosting scene
  34046. * @param radius defines the radius of the disc
  34047. * @param tessellation defines the tesselation factor to apply to the disc
  34048. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34049. * @param mesh defines the hosting mesh (can be null)
  34050. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34051. */
  34052. function DiscGeometry(id, scene,
  34053. /**
  34054. * Defines the radius of the disc
  34055. */
  34056. radius,
  34057. /**
  34058. * Defines the tesselation factor to apply to the disc
  34059. */
  34060. tessellation, canBeRegenerated, mesh,
  34061. /**
  34062. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34063. */
  34064. side) {
  34065. if (mesh === void 0) { mesh = null; }
  34066. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34067. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34068. _this.radius = radius;
  34069. _this.tessellation = tessellation;
  34070. _this.side = side;
  34071. return _this;
  34072. }
  34073. DiscGeometry.prototype._regenerateVertexData = function () {
  34074. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34075. };
  34076. DiscGeometry.prototype.copy = function (id) {
  34077. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34078. };
  34079. return DiscGeometry;
  34080. }(_PrimitiveGeometry));
  34081. BABYLON.DiscGeometry = DiscGeometry;
  34082. /**
  34083. * Creates a new cylinder geometry
  34084. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  34085. */
  34086. var CylinderGeometry = /** @class */ (function (_super) {
  34087. __extends(CylinderGeometry, _super);
  34088. /**
  34089. * Creates a new cylinder geometry
  34090. * @param id defines the unique ID of the geometry
  34091. * @param scene defines the hosting scene
  34092. * @param height defines the height of the cylinder
  34093. * @param diameterTop defines the diameter of the cylinder's top cap
  34094. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  34095. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  34096. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  34097. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34098. * @param mesh defines the hosting mesh (can be null)
  34099. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34100. */
  34101. function CylinderGeometry(id, scene,
  34102. /**
  34103. * Defines the height of the cylinder
  34104. */
  34105. height,
  34106. /**
  34107. * Defines the diameter of the cylinder's top cap
  34108. */
  34109. diameterTop,
  34110. /**
  34111. * Defines the diameter of the cylinder's bottom cap
  34112. */
  34113. diameterBottom,
  34114. /**
  34115. * Defines the tessellation factor to apply to the cylinder
  34116. */
  34117. tessellation,
  34118. /**
  34119. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  34120. */
  34121. subdivisions, canBeRegenerated, mesh,
  34122. /**
  34123. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34124. */
  34125. side) {
  34126. if (subdivisions === void 0) { subdivisions = 1; }
  34127. if (mesh === void 0) { mesh = null; }
  34128. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34129. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34130. _this.height = height;
  34131. _this.diameterTop = diameterTop;
  34132. _this.diameterBottom = diameterBottom;
  34133. _this.tessellation = tessellation;
  34134. _this.subdivisions = subdivisions;
  34135. _this.side = side;
  34136. return _this;
  34137. }
  34138. CylinderGeometry.prototype._regenerateVertexData = function () {
  34139. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34140. };
  34141. CylinderGeometry.prototype.copy = function (id) {
  34142. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34143. };
  34144. CylinderGeometry.prototype.serialize = function () {
  34145. var serializationObject = _super.prototype.serialize.call(this);
  34146. serializationObject.height = this.height;
  34147. serializationObject.diameterTop = this.diameterTop;
  34148. serializationObject.diameterBottom = this.diameterBottom;
  34149. serializationObject.tessellation = this.tessellation;
  34150. return serializationObject;
  34151. };
  34152. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34153. if (scene.getGeometryByID(parsedCylinder.id)) {
  34154. return null; // null since geometry could be something else than a cylinder...
  34155. }
  34156. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34157. if (BABYLON.Tags) {
  34158. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34159. }
  34160. scene.pushGeometry(cylinder, true);
  34161. return cylinder;
  34162. };
  34163. return CylinderGeometry;
  34164. }(_PrimitiveGeometry));
  34165. BABYLON.CylinderGeometry = CylinderGeometry;
  34166. /**
  34167. * Creates a new torus geometry
  34168. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34169. */
  34170. var TorusGeometry = /** @class */ (function (_super) {
  34171. __extends(TorusGeometry, _super);
  34172. /**
  34173. * Creates a new torus geometry
  34174. * @param id defines the unique ID of the geometry
  34175. * @param scene defines the hosting scene
  34176. * @param diameter defines the diameter of the torus
  34177. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34178. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34179. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34180. * @param mesh defines the hosting mesh (can be null)
  34181. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34182. */
  34183. function TorusGeometry(id, scene,
  34184. /**
  34185. * Defines the diameter of the torus
  34186. */
  34187. diameter,
  34188. /**
  34189. * Defines the thickness of the torus (ie. internal diameter)
  34190. */
  34191. thickness,
  34192. /**
  34193. * Defines the tesselation factor to apply to the torus
  34194. */
  34195. tessellation, canBeRegenerated, mesh,
  34196. /**
  34197. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34198. */
  34199. side) {
  34200. if (mesh === void 0) { mesh = null; }
  34201. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34202. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34203. _this.diameter = diameter;
  34204. _this.thickness = thickness;
  34205. _this.tessellation = tessellation;
  34206. _this.side = side;
  34207. return _this;
  34208. }
  34209. TorusGeometry.prototype._regenerateVertexData = function () {
  34210. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34211. };
  34212. TorusGeometry.prototype.copy = function (id) {
  34213. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34214. };
  34215. TorusGeometry.prototype.serialize = function () {
  34216. var serializationObject = _super.prototype.serialize.call(this);
  34217. serializationObject.diameter = this.diameter;
  34218. serializationObject.thickness = this.thickness;
  34219. serializationObject.tessellation = this.tessellation;
  34220. return serializationObject;
  34221. };
  34222. TorusGeometry.Parse = function (parsedTorus, scene) {
  34223. if (scene.getGeometryByID(parsedTorus.id)) {
  34224. return null; // null since geometry could be something else than a torus...
  34225. }
  34226. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34227. if (BABYLON.Tags) {
  34228. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34229. }
  34230. scene.pushGeometry(torus, true);
  34231. return torus;
  34232. };
  34233. return TorusGeometry;
  34234. }(_PrimitiveGeometry));
  34235. BABYLON.TorusGeometry = TorusGeometry;
  34236. /**
  34237. * Creates a new ground geometry
  34238. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34239. */
  34240. var GroundGeometry = /** @class */ (function (_super) {
  34241. __extends(GroundGeometry, _super);
  34242. /**
  34243. * Creates a new ground geometry
  34244. * @param id defines the unique ID of the geometry
  34245. * @param scene defines the hosting scene
  34246. * @param width defines the width of the ground
  34247. * @param height defines the height of the ground
  34248. * @param subdivisions defines the subdivisions to apply to the ground
  34249. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34250. * @param mesh defines the hosting mesh (can be null)
  34251. */
  34252. function GroundGeometry(id, scene,
  34253. /**
  34254. * Defines the width of the ground
  34255. */
  34256. width,
  34257. /**
  34258. * Defines the height of the ground
  34259. */
  34260. height,
  34261. /**
  34262. * Defines the subdivisions to apply to the ground
  34263. */
  34264. subdivisions, canBeRegenerated, mesh) {
  34265. if (mesh === void 0) { mesh = null; }
  34266. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34267. _this.width = width;
  34268. _this.height = height;
  34269. _this.subdivisions = subdivisions;
  34270. return _this;
  34271. }
  34272. GroundGeometry.prototype._regenerateVertexData = function () {
  34273. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34274. };
  34275. GroundGeometry.prototype.copy = function (id) {
  34276. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34277. };
  34278. GroundGeometry.prototype.serialize = function () {
  34279. var serializationObject = _super.prototype.serialize.call(this);
  34280. serializationObject.width = this.width;
  34281. serializationObject.height = this.height;
  34282. serializationObject.subdivisions = this.subdivisions;
  34283. return serializationObject;
  34284. };
  34285. GroundGeometry.Parse = function (parsedGround, scene) {
  34286. if (scene.getGeometryByID(parsedGround.id)) {
  34287. return null; // null since geometry could be something else than a ground...
  34288. }
  34289. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34290. if (BABYLON.Tags) {
  34291. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34292. }
  34293. scene.pushGeometry(ground, true);
  34294. return ground;
  34295. };
  34296. return GroundGeometry;
  34297. }(_PrimitiveGeometry));
  34298. BABYLON.GroundGeometry = GroundGeometry;
  34299. /**
  34300. * Creates a tiled ground geometry
  34301. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34302. */
  34303. var TiledGroundGeometry = /** @class */ (function (_super) {
  34304. __extends(TiledGroundGeometry, _super);
  34305. /**
  34306. * Creates a tiled ground geometry
  34307. * @param id defines the unique ID of the geometry
  34308. * @param scene defines the hosting scene
  34309. * @param xmin defines the minimum value on X axis
  34310. * @param zmin defines the minimum value on Z axis
  34311. * @param xmax defines the maximum value on X axis
  34312. * @param zmax defines the maximum value on Z axis
  34313. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34314. * @param precision defines the precision to use when computing the tiles
  34315. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34316. * @param mesh defines the hosting mesh (can be null)
  34317. */
  34318. function TiledGroundGeometry(id, scene,
  34319. /**
  34320. * Defines the minimum value on X axis
  34321. */
  34322. xmin,
  34323. /**
  34324. * Defines the minimum value on Z axis
  34325. */
  34326. zmin,
  34327. /**
  34328. * Defines the maximum value on X axis
  34329. */
  34330. xmax,
  34331. /**
  34332. * Defines the maximum value on Z axis
  34333. */
  34334. zmax,
  34335. /**
  34336. * Defines the subdivisions to apply to the ground
  34337. */
  34338. subdivisions,
  34339. /**
  34340. * Defines the precision to use when computing the tiles
  34341. */
  34342. precision, canBeRegenerated, mesh) {
  34343. if (mesh === void 0) { mesh = null; }
  34344. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34345. _this.xmin = xmin;
  34346. _this.zmin = zmin;
  34347. _this.xmax = xmax;
  34348. _this.zmax = zmax;
  34349. _this.subdivisions = subdivisions;
  34350. _this.precision = precision;
  34351. return _this;
  34352. }
  34353. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34354. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34355. };
  34356. TiledGroundGeometry.prototype.copy = function (id) {
  34357. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34358. };
  34359. return TiledGroundGeometry;
  34360. }(_PrimitiveGeometry));
  34361. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34362. /**
  34363. * Creates a plane geometry
  34364. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34365. */
  34366. var PlaneGeometry = /** @class */ (function (_super) {
  34367. __extends(PlaneGeometry, _super);
  34368. /**
  34369. * Creates a plane geometry
  34370. * @param id defines the unique ID of the geometry
  34371. * @param scene defines the hosting scene
  34372. * @param size defines the size of the plane (width === height)
  34373. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34374. * @param mesh defines the hosting mesh (can be null)
  34375. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34376. */
  34377. function PlaneGeometry(id, scene,
  34378. /**
  34379. * Defines the size of the plane (width === height)
  34380. */
  34381. size, canBeRegenerated, mesh,
  34382. /**
  34383. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34384. */
  34385. side) {
  34386. if (mesh === void 0) { mesh = null; }
  34387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34388. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34389. _this.size = size;
  34390. _this.side = side;
  34391. return _this;
  34392. }
  34393. PlaneGeometry.prototype._regenerateVertexData = function () {
  34394. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34395. };
  34396. PlaneGeometry.prototype.copy = function (id) {
  34397. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34398. };
  34399. PlaneGeometry.prototype.serialize = function () {
  34400. var serializationObject = _super.prototype.serialize.call(this);
  34401. serializationObject.size = this.size;
  34402. return serializationObject;
  34403. };
  34404. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34405. if (scene.getGeometryByID(parsedPlane.id)) {
  34406. return null; // null since geometry could be something else than a ground...
  34407. }
  34408. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34409. if (BABYLON.Tags) {
  34410. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34411. }
  34412. scene.pushGeometry(plane, true);
  34413. return plane;
  34414. };
  34415. return PlaneGeometry;
  34416. }(_PrimitiveGeometry));
  34417. BABYLON.PlaneGeometry = PlaneGeometry;
  34418. /**
  34419. * Creates a torus knot geometry
  34420. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34421. */
  34422. var TorusKnotGeometry = /** @class */ (function (_super) {
  34423. __extends(TorusKnotGeometry, _super);
  34424. /**
  34425. * Creates a torus knot geometry
  34426. * @param id defines the unique ID of the geometry
  34427. * @param scene defines the hosting scene
  34428. * @param radius defines the radius of the torus knot
  34429. * @param tube defines the thickness of the torus knot tube
  34430. * @param radialSegments defines the number of radial segments
  34431. * @param tubularSegments defines the number of tubular segments
  34432. * @param p defines the first number of windings
  34433. * @param q defines the second number of windings
  34434. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34435. * @param mesh defines the hosting mesh (can be null)
  34436. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34437. */
  34438. function TorusKnotGeometry(id, scene,
  34439. /**
  34440. * Defines the radius of the torus knot
  34441. */
  34442. radius,
  34443. /**
  34444. * Defines the thickness of the torus knot tube
  34445. */
  34446. tube,
  34447. /**
  34448. * Defines the number of radial segments
  34449. */
  34450. radialSegments,
  34451. /**
  34452. * Defines the number of tubular segments
  34453. */
  34454. tubularSegments,
  34455. /**
  34456. * Defines the first number of windings
  34457. */
  34458. p,
  34459. /**
  34460. * Defines the second number of windings
  34461. */
  34462. q, canBeRegenerated, mesh,
  34463. /**
  34464. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34465. */
  34466. side) {
  34467. if (mesh === void 0) { mesh = null; }
  34468. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34469. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34470. _this.radius = radius;
  34471. _this.tube = tube;
  34472. _this.radialSegments = radialSegments;
  34473. _this.tubularSegments = tubularSegments;
  34474. _this.p = p;
  34475. _this.q = q;
  34476. _this.side = side;
  34477. return _this;
  34478. }
  34479. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34480. 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 });
  34481. };
  34482. TorusKnotGeometry.prototype.copy = function (id) {
  34483. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34484. };
  34485. TorusKnotGeometry.prototype.serialize = function () {
  34486. var serializationObject = _super.prototype.serialize.call(this);
  34487. serializationObject.radius = this.radius;
  34488. serializationObject.tube = this.tube;
  34489. serializationObject.radialSegments = this.radialSegments;
  34490. serializationObject.tubularSegments = this.tubularSegments;
  34491. serializationObject.p = this.p;
  34492. serializationObject.q = this.q;
  34493. return serializationObject;
  34494. };
  34495. ;
  34496. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34497. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34498. return null; // null since geometry could be something else than a ground...
  34499. }
  34500. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34501. if (BABYLON.Tags) {
  34502. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34503. }
  34504. scene.pushGeometry(torusKnot, true);
  34505. return torusKnot;
  34506. };
  34507. return TorusKnotGeometry;
  34508. }(_PrimitiveGeometry));
  34509. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34510. //}
  34511. })(BABYLON || (BABYLON = {}));
  34512. //# sourceMappingURL=babylon.geometry.js.map
  34513. var BABYLON;
  34514. (function (BABYLON) {
  34515. var PostProcessManager = /** @class */ (function () {
  34516. function PostProcessManager(scene) {
  34517. this._vertexBuffers = {};
  34518. this._scene = scene;
  34519. }
  34520. PostProcessManager.prototype._prepareBuffers = function () {
  34521. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34522. return;
  34523. }
  34524. // VBO
  34525. var vertices = [];
  34526. vertices.push(1, 1);
  34527. vertices.push(-1, 1);
  34528. vertices.push(-1, -1);
  34529. vertices.push(1, -1);
  34530. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34531. this._buildIndexBuffer();
  34532. };
  34533. PostProcessManager.prototype._buildIndexBuffer = function () {
  34534. // Indices
  34535. var indices = [];
  34536. indices.push(0);
  34537. indices.push(1);
  34538. indices.push(2);
  34539. indices.push(0);
  34540. indices.push(2);
  34541. indices.push(3);
  34542. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34543. };
  34544. PostProcessManager.prototype._rebuild = function () {
  34545. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34546. if (!vb) {
  34547. return;
  34548. }
  34549. vb._rebuild();
  34550. this._buildIndexBuffer();
  34551. };
  34552. // Methods
  34553. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34554. if (sourceTexture === void 0) { sourceTexture = null; }
  34555. if (postProcesses === void 0) { postProcesses = null; }
  34556. var camera = this._scene.activeCamera;
  34557. if (!camera) {
  34558. return false;
  34559. }
  34560. var postProcesses = postProcesses || camera._postProcesses;
  34561. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34562. return false;
  34563. }
  34564. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34565. return true;
  34566. };
  34567. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34568. if (targetTexture === void 0) { targetTexture = null; }
  34569. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34570. var engine = this._scene.getEngine();
  34571. for (var index = 0; index < postProcesses.length; index++) {
  34572. if (index < postProcesses.length - 1) {
  34573. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34574. }
  34575. else {
  34576. if (targetTexture) {
  34577. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34578. }
  34579. else {
  34580. engine.restoreDefaultFramebuffer();
  34581. }
  34582. }
  34583. var pp = postProcesses[index];
  34584. var effect = pp.apply();
  34585. if (effect) {
  34586. pp.onBeforeRenderObservable.notifyObservers(effect);
  34587. // VBOs
  34588. this._prepareBuffers();
  34589. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34590. // Draw order
  34591. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34592. pp.onAfterRenderObservable.notifyObservers(effect);
  34593. }
  34594. }
  34595. // Restore depth buffer
  34596. engine.setDepthBuffer(true);
  34597. engine.setDepthWrite(true);
  34598. };
  34599. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34600. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34601. var camera = this._scene.activeCamera;
  34602. if (!camera) {
  34603. return;
  34604. }
  34605. postProcesses = postProcesses || camera._postProcesses;
  34606. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34607. return;
  34608. }
  34609. var engine = this._scene.getEngine();
  34610. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34611. if (index < len - 1) {
  34612. postProcesses[index + 1].activate(camera, targetTexture);
  34613. }
  34614. else {
  34615. if (targetTexture) {
  34616. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34617. }
  34618. else {
  34619. engine.restoreDefaultFramebuffer();
  34620. }
  34621. }
  34622. if (doNotPresent) {
  34623. break;
  34624. }
  34625. var pp = postProcesses[index];
  34626. var effect = pp.apply();
  34627. if (effect) {
  34628. pp.onBeforeRenderObservable.notifyObservers(effect);
  34629. // VBOs
  34630. this._prepareBuffers();
  34631. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34632. // Draw order
  34633. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34634. pp.onAfterRenderObservable.notifyObservers(effect);
  34635. }
  34636. }
  34637. // Restore states
  34638. engine.setDepthBuffer(true);
  34639. engine.setDepthWrite(true);
  34640. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34641. };
  34642. PostProcessManager.prototype.dispose = function () {
  34643. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34644. if (buffer) {
  34645. buffer.dispose();
  34646. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34647. }
  34648. if (this._indexBuffer) {
  34649. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34650. this._indexBuffer = null;
  34651. }
  34652. };
  34653. return PostProcessManager;
  34654. }());
  34655. BABYLON.PostProcessManager = PostProcessManager;
  34656. })(BABYLON || (BABYLON = {}));
  34657. //# sourceMappingURL=babylon.postProcessManager.js.map
  34658. var BABYLON;
  34659. (function (BABYLON) {
  34660. /**
  34661. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34662. */
  34663. var PerformanceMonitor = /** @class */ (function () {
  34664. /**
  34665. * constructor
  34666. * @param frameSampleSize The number of samples required to saturate the sliding window
  34667. */
  34668. function PerformanceMonitor(frameSampleSize) {
  34669. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34670. this._enabled = true;
  34671. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34672. }
  34673. /**
  34674. * Samples current frame
  34675. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34676. */
  34677. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34678. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34679. if (!this._enabled)
  34680. return;
  34681. if (this._lastFrameTimeMs != null) {
  34682. var dt = timeMs - this._lastFrameTimeMs;
  34683. this._rollingFrameTime.add(dt);
  34684. }
  34685. this._lastFrameTimeMs = timeMs;
  34686. };
  34687. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34688. /**
  34689. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34690. * @return Average frame time in milliseconds
  34691. */
  34692. get: function () {
  34693. return this._rollingFrameTime.average;
  34694. },
  34695. enumerable: true,
  34696. configurable: true
  34697. });
  34698. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34699. /**
  34700. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34701. * @return Frame time variance in milliseconds squared
  34702. */
  34703. get: function () {
  34704. return this._rollingFrameTime.variance;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34710. /**
  34711. * Returns the frame time of the most recent frame
  34712. * @return Frame time in milliseconds
  34713. */
  34714. get: function () {
  34715. return this._rollingFrameTime.history(0);
  34716. },
  34717. enumerable: true,
  34718. configurable: true
  34719. });
  34720. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34721. /**
  34722. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34723. * @return Framerate in frames per second
  34724. */
  34725. get: function () {
  34726. return 1000.0 / this._rollingFrameTime.average;
  34727. },
  34728. enumerable: true,
  34729. configurable: true
  34730. });
  34731. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34732. /**
  34733. * Returns the average framerate in frames per second using the most recent frame time
  34734. * @return Framerate in frames per second
  34735. */
  34736. get: function () {
  34737. var history = this._rollingFrameTime.history(0);
  34738. if (history === 0) {
  34739. return 0;
  34740. }
  34741. return 1000.0 / history;
  34742. },
  34743. enumerable: true,
  34744. configurable: true
  34745. });
  34746. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34747. /**
  34748. * Returns true if enough samples have been taken to completely fill the sliding window
  34749. * @return true if saturated
  34750. */
  34751. get: function () {
  34752. return this._rollingFrameTime.isSaturated();
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. /**
  34758. * Enables contributions to the sliding window sample set
  34759. */
  34760. PerformanceMonitor.prototype.enable = function () {
  34761. this._enabled = true;
  34762. };
  34763. /**
  34764. * Disables contributions to the sliding window sample set
  34765. * Samples will not be interpolated over the disabled period
  34766. */
  34767. PerformanceMonitor.prototype.disable = function () {
  34768. this._enabled = false;
  34769. //clear last sample to avoid interpolating over the disabled period when next enabled
  34770. this._lastFrameTimeMs = null;
  34771. };
  34772. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34773. /**
  34774. * Returns true if sampling is enabled
  34775. * @return true if enabled
  34776. */
  34777. get: function () {
  34778. return this._enabled;
  34779. },
  34780. enumerable: true,
  34781. configurable: true
  34782. });
  34783. /**
  34784. * Resets performance monitor
  34785. */
  34786. PerformanceMonitor.prototype.reset = function () {
  34787. //clear last sample to avoid interpolating over the disabled period when next enabled
  34788. this._lastFrameTimeMs = null;
  34789. //wipe record
  34790. this._rollingFrameTime.reset();
  34791. };
  34792. return PerformanceMonitor;
  34793. }());
  34794. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34795. /**
  34796. * RollingAverage
  34797. *
  34798. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34799. */
  34800. var RollingAverage = /** @class */ (function () {
  34801. /**
  34802. * constructor
  34803. * @param length The number of samples required to saturate the sliding window
  34804. */
  34805. function RollingAverage(length) {
  34806. this._samples = new Array(length);
  34807. this.reset();
  34808. }
  34809. /**
  34810. * Adds a sample to the sample set
  34811. * @param v The sample value
  34812. */
  34813. RollingAverage.prototype.add = function (v) {
  34814. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34815. var delta;
  34816. //we need to check if we've already wrapped round
  34817. if (this.isSaturated()) {
  34818. //remove bottom of stack from mean
  34819. var bottomValue = this._samples[this._pos];
  34820. delta = bottomValue - this.average;
  34821. this.average -= delta / (this._sampleCount - 1);
  34822. this._m2 -= delta * (bottomValue - this.average);
  34823. }
  34824. else {
  34825. this._sampleCount++;
  34826. }
  34827. //add new value to mean
  34828. delta = v - this.average;
  34829. this.average += delta / (this._sampleCount);
  34830. this._m2 += delta * (v - this.average);
  34831. //set the new variance
  34832. this.variance = this._m2 / (this._sampleCount - 1);
  34833. this._samples[this._pos] = v;
  34834. this._pos++;
  34835. this._pos %= this._samples.length; //positive wrap around
  34836. };
  34837. /**
  34838. * Returns previously added values or null if outside of history or outside the sliding window domain
  34839. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34840. * @return Value previously recorded with add() or null if outside of range
  34841. */
  34842. RollingAverage.prototype.history = function (i) {
  34843. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34844. return 0;
  34845. }
  34846. var i0 = this._wrapPosition(this._pos - 1.0);
  34847. return this._samples[this._wrapPosition(i0 - i)];
  34848. };
  34849. /**
  34850. * Returns true if enough samples have been taken to completely fill the sliding window
  34851. * @return true if sample-set saturated
  34852. */
  34853. RollingAverage.prototype.isSaturated = function () {
  34854. return this._sampleCount >= this._samples.length;
  34855. };
  34856. /**
  34857. * Resets the rolling average (equivalent to 0 samples taken so far)
  34858. */
  34859. RollingAverage.prototype.reset = function () {
  34860. this.average = 0;
  34861. this.variance = 0;
  34862. this._sampleCount = 0;
  34863. this._pos = 0;
  34864. this._m2 = 0;
  34865. };
  34866. /**
  34867. * Wraps a value around the sample range boundaries
  34868. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34869. * @return Wrapped position in sample range
  34870. */
  34871. RollingAverage.prototype._wrapPosition = function (i) {
  34872. var max = this._samples.length;
  34873. return ((i % max) + max) % max;
  34874. };
  34875. return RollingAverage;
  34876. }());
  34877. BABYLON.RollingAverage = RollingAverage;
  34878. })(BABYLON || (BABYLON = {}));
  34879. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34880. var BABYLON;
  34881. (function (BABYLON) {
  34882. /**
  34883. * This groups together the common properties used for image processing either in direct forward pass
  34884. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34885. * or not.
  34886. */
  34887. var ImageProcessingConfiguration = /** @class */ (function () {
  34888. function ImageProcessingConfiguration() {
  34889. /**
  34890. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34891. */
  34892. this.colorCurves = new BABYLON.ColorCurves();
  34893. this._colorCurvesEnabled = false;
  34894. this._colorGradingEnabled = false;
  34895. this._colorGradingWithGreenDepth = true;
  34896. this._colorGradingBGR = true;
  34897. this._exposure = 1.0;
  34898. this._toneMappingEnabled = false;
  34899. this._contrast = 1.0;
  34900. /**
  34901. * Vignette stretch size.
  34902. */
  34903. this.vignetteStretch = 0;
  34904. /**
  34905. * Vignette centre X Offset.
  34906. */
  34907. this.vignetteCentreX = 0;
  34908. /**
  34909. * Vignette centre Y Offset.
  34910. */
  34911. this.vignetteCentreY = 0;
  34912. /**
  34913. * Vignette weight or intensity of the vignette effect.
  34914. */
  34915. this.vignetteWeight = 1.5;
  34916. /**
  34917. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34918. * if vignetteEnabled is set to true.
  34919. */
  34920. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34921. /**
  34922. * Camera field of view used by the Vignette effect.
  34923. */
  34924. this.vignetteCameraFov = 0.5;
  34925. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34926. this._vignetteEnabled = false;
  34927. this._applyByPostProcess = false;
  34928. this._isEnabled = true;
  34929. /**
  34930. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34931. * @type {BABYLON.Observable}
  34932. */
  34933. this.onUpdateParameters = new BABYLON.Observable();
  34934. }
  34935. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34936. /**
  34937. * Gets wether the color curves effect is enabled.
  34938. */
  34939. get: function () {
  34940. return this._colorCurvesEnabled;
  34941. },
  34942. /**
  34943. * Sets wether the color curves effect is enabled.
  34944. */
  34945. set: function (value) {
  34946. if (this._colorCurvesEnabled === value) {
  34947. return;
  34948. }
  34949. this._colorCurvesEnabled = value;
  34950. this._updateParameters();
  34951. },
  34952. enumerable: true,
  34953. configurable: true
  34954. });
  34955. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34956. /**
  34957. * Gets wether the color grading effect is enabled.
  34958. */
  34959. get: function () {
  34960. return this._colorGradingEnabled;
  34961. },
  34962. /**
  34963. * Sets wether the color grading effect is enabled.
  34964. */
  34965. set: function (value) {
  34966. if (this._colorGradingEnabled === value) {
  34967. return;
  34968. }
  34969. this._colorGradingEnabled = value;
  34970. this._updateParameters();
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34976. /**
  34977. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34978. */
  34979. get: function () {
  34980. return this._colorGradingWithGreenDepth;
  34981. },
  34982. /**
  34983. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34984. */
  34985. set: function (value) {
  34986. if (this._colorGradingWithGreenDepth === value) {
  34987. return;
  34988. }
  34989. this._colorGradingWithGreenDepth = value;
  34990. this._updateParameters();
  34991. },
  34992. enumerable: true,
  34993. configurable: true
  34994. });
  34995. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34996. /**
  34997. * Gets wether the color grading texture contains BGR values.
  34998. */
  34999. get: function () {
  35000. return this._colorGradingBGR;
  35001. },
  35002. /**
  35003. * Sets wether the color grading texture contains BGR values.
  35004. */
  35005. set: function (value) {
  35006. if (this._colorGradingBGR === value) {
  35007. return;
  35008. }
  35009. this._colorGradingBGR = value;
  35010. this._updateParameters();
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  35016. /**
  35017. * Gets the Exposure used in the effect.
  35018. */
  35019. get: function () {
  35020. return this._exposure;
  35021. },
  35022. /**
  35023. * Sets the Exposure used in the effect.
  35024. */
  35025. set: function (value) {
  35026. if (this._exposure === value) {
  35027. return;
  35028. }
  35029. this._exposure = value;
  35030. this._updateParameters();
  35031. },
  35032. enumerable: true,
  35033. configurable: true
  35034. });
  35035. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  35036. /**
  35037. * Gets wether the tone mapping effect is enabled.
  35038. */
  35039. get: function () {
  35040. return this._toneMappingEnabled;
  35041. },
  35042. /**
  35043. * Sets wether the tone mapping effect is enabled.
  35044. */
  35045. set: function (value) {
  35046. if (this._toneMappingEnabled === value) {
  35047. return;
  35048. }
  35049. this._toneMappingEnabled = value;
  35050. this._updateParameters();
  35051. },
  35052. enumerable: true,
  35053. configurable: true
  35054. });
  35055. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  35056. /**
  35057. * Gets the contrast used in the effect.
  35058. */
  35059. get: function () {
  35060. return this._contrast;
  35061. },
  35062. /**
  35063. * Sets the contrast used in the effect.
  35064. */
  35065. set: function (value) {
  35066. if (this._contrast === value) {
  35067. return;
  35068. }
  35069. this._contrast = value;
  35070. this._updateParameters();
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  35076. /**
  35077. * Gets the vignette blend mode allowing different kind of effect.
  35078. */
  35079. get: function () {
  35080. return this._vignetteBlendMode;
  35081. },
  35082. /**
  35083. * Sets the vignette blend mode allowing different kind of effect.
  35084. */
  35085. set: function (value) {
  35086. if (this._vignetteBlendMode === value) {
  35087. return;
  35088. }
  35089. this._vignetteBlendMode = value;
  35090. this._updateParameters();
  35091. },
  35092. enumerable: true,
  35093. configurable: true
  35094. });
  35095. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  35096. /**
  35097. * Gets wether the vignette effect is enabled.
  35098. */
  35099. get: function () {
  35100. return this._vignetteEnabled;
  35101. },
  35102. /**
  35103. * Sets wether the vignette effect is enabled.
  35104. */
  35105. set: function (value) {
  35106. if (this._vignetteEnabled === value) {
  35107. return;
  35108. }
  35109. this._vignetteEnabled = value;
  35110. this._updateParameters();
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  35116. /**
  35117. * Gets wether the image processing is applied through a post process or not.
  35118. */
  35119. get: function () {
  35120. return this._applyByPostProcess;
  35121. },
  35122. /**
  35123. * Sets wether the image processing is applied through a post process or not.
  35124. */
  35125. set: function (value) {
  35126. if (this._applyByPostProcess === value) {
  35127. return;
  35128. }
  35129. this._applyByPostProcess = value;
  35130. this._updateParameters();
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  35136. /**
  35137. * Gets wether the image processing is enabled or not.
  35138. */
  35139. get: function () {
  35140. return this._isEnabled;
  35141. },
  35142. /**
  35143. * Sets wether the image processing is enabled or not.
  35144. */
  35145. set: function (value) {
  35146. if (this._isEnabled === value) {
  35147. return;
  35148. }
  35149. this._isEnabled = value;
  35150. this._updateParameters();
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. /**
  35156. * Method called each time the image processing information changes requires to recompile the effect.
  35157. */
  35158. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35159. this.onUpdateParameters.notifyObservers(this);
  35160. };
  35161. ImageProcessingConfiguration.prototype.getClassName = function () {
  35162. return "ImageProcessingConfiguration";
  35163. };
  35164. /**
  35165. * Prepare the list of uniforms associated with the Image Processing effects.
  35166. * @param uniformsList The list of uniforms used in the effect
  35167. * @param defines the list of defines currently in use
  35168. */
  35169. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35170. if (defines.EXPOSURE) {
  35171. uniforms.push("exposureLinear");
  35172. }
  35173. if (defines.CONTRAST) {
  35174. uniforms.push("contrast");
  35175. }
  35176. if (defines.COLORGRADING) {
  35177. uniforms.push("colorTransformSettings");
  35178. }
  35179. if (defines.VIGNETTE) {
  35180. uniforms.push("vInverseScreenSize");
  35181. uniforms.push("vignetteSettings1");
  35182. uniforms.push("vignetteSettings2");
  35183. }
  35184. if (defines.COLORCURVES) {
  35185. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35186. }
  35187. };
  35188. /**
  35189. * Prepare the list of samplers associated with the Image Processing effects.
  35190. * @param uniformsList The list of uniforms used in the effect
  35191. * @param defines the list of defines currently in use
  35192. */
  35193. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35194. if (defines.COLORGRADING) {
  35195. samplersList.push("txColorTransform");
  35196. }
  35197. };
  35198. /**
  35199. * Prepare the list of defines associated to the shader.
  35200. * @param defines the list of defines to complete
  35201. */
  35202. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35203. if (forPostProcess === void 0) { forPostProcess = false; }
  35204. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35205. defines.VIGNETTE = false;
  35206. defines.TONEMAPPING = false;
  35207. defines.CONTRAST = false;
  35208. defines.EXPOSURE = false;
  35209. defines.COLORCURVES = false;
  35210. defines.COLORGRADING = false;
  35211. defines.COLORGRADING3D = false;
  35212. defines.IMAGEPROCESSING = false;
  35213. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35214. return;
  35215. }
  35216. defines.VIGNETTE = this.vignetteEnabled;
  35217. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35218. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35219. defines.TONEMAPPING = this.toneMappingEnabled;
  35220. defines.CONTRAST = (this.contrast !== 1.0);
  35221. defines.EXPOSURE = (this.exposure !== 1.0);
  35222. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35223. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35224. if (defines.COLORGRADING) {
  35225. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35226. }
  35227. else {
  35228. defines.COLORGRADING3D = false;
  35229. }
  35230. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35231. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35232. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35233. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35234. };
  35235. /**
  35236. * Returns true if all the image processing information are ready.
  35237. */
  35238. ImageProcessingConfiguration.prototype.isReady = function () {
  35239. // Color Grading texure can not be none blocking.
  35240. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35241. };
  35242. /**
  35243. * Binds the image processing to the shader.
  35244. * @param effect The effect to bind to
  35245. */
  35246. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35247. if (aspectRatio === void 0) { aspectRatio = 1; }
  35248. // Color Curves
  35249. if (this._colorCurvesEnabled && this.colorCurves) {
  35250. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35251. }
  35252. // Vignette
  35253. if (this._vignetteEnabled) {
  35254. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35255. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35256. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35257. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35258. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35259. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35260. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35261. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35262. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35263. var vignettePower = -2.0 * this.vignetteWeight;
  35264. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35265. }
  35266. // Exposure
  35267. effect.setFloat("exposureLinear", this.exposure);
  35268. // Contrast
  35269. effect.setFloat("contrast", this.contrast);
  35270. // Color transform settings
  35271. if (this.colorGradingTexture) {
  35272. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35273. var textureSize = this.colorGradingTexture.getSize().height;
  35274. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35275. 0.5 / textureSize, // textureOffset
  35276. textureSize, // textureSize
  35277. this.colorGradingTexture.level // weight
  35278. );
  35279. }
  35280. };
  35281. /**
  35282. * Clones the current image processing instance.
  35283. * @return The cloned image processing
  35284. */
  35285. ImageProcessingConfiguration.prototype.clone = function () {
  35286. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35287. };
  35288. /**
  35289. * Serializes the current image processing instance to a json representation.
  35290. * @return a JSON representation
  35291. */
  35292. ImageProcessingConfiguration.prototype.serialize = function () {
  35293. return BABYLON.SerializationHelper.Serialize(this);
  35294. };
  35295. /**
  35296. * Parses the image processing from a json representation.
  35297. * @param source the JSON source to parse
  35298. * @return The parsed image processing
  35299. */
  35300. ImageProcessingConfiguration.Parse = function (source) {
  35301. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35302. };
  35303. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35304. /**
  35305. * Used to apply the vignette as a mix with the pixel color.
  35306. */
  35307. get: function () {
  35308. return this._VIGNETTEMODE_MULTIPLY;
  35309. },
  35310. enumerable: true,
  35311. configurable: true
  35312. });
  35313. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35314. /**
  35315. * Used to apply the vignette as a replacement of the pixel color.
  35316. */
  35317. get: function () {
  35318. return this._VIGNETTEMODE_OPAQUE;
  35319. },
  35320. enumerable: true,
  35321. configurable: true
  35322. });
  35323. // Static constants associated to the image processing.
  35324. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35325. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35326. __decorate([
  35327. BABYLON.serializeAsColorCurves()
  35328. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35329. __decorate([
  35330. BABYLON.serialize()
  35331. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35332. __decorate([
  35333. BABYLON.serializeAsTexture()
  35334. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35335. __decorate([
  35336. BABYLON.serialize()
  35337. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35338. __decorate([
  35339. BABYLON.serialize()
  35340. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35341. __decorate([
  35342. BABYLON.serialize()
  35343. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35344. __decorate([
  35345. BABYLON.serialize()
  35346. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35347. __decorate([
  35348. BABYLON.serialize()
  35349. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35350. __decorate([
  35351. BABYLON.serialize()
  35352. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35353. __decorate([
  35354. BABYLON.serialize()
  35355. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35356. __decorate([
  35357. BABYLON.serialize()
  35358. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35359. __decorate([
  35360. BABYLON.serialize()
  35361. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35362. __decorate([
  35363. BABYLON.serialize()
  35364. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35365. __decorate([
  35366. BABYLON.serializeAsColor4()
  35367. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35368. __decorate([
  35369. BABYLON.serialize()
  35370. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35371. __decorate([
  35372. BABYLON.serialize()
  35373. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35374. __decorate([
  35375. BABYLON.serialize()
  35376. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35377. __decorate([
  35378. BABYLON.serialize()
  35379. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35380. __decorate([
  35381. BABYLON.serialize()
  35382. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35383. return ImageProcessingConfiguration;
  35384. }());
  35385. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35386. })(BABYLON || (BABYLON = {}));
  35387. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35388. var BABYLON;
  35389. (function (BABYLON) {
  35390. /**
  35391. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35392. * It can help converting any input color in a desired output one. This can then be used to create effects
  35393. * from sepia, black and white to sixties or futuristic rendering...
  35394. *
  35395. * The only supported format is currently 3dl.
  35396. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35397. */
  35398. var ColorGradingTexture = /** @class */ (function (_super) {
  35399. __extends(ColorGradingTexture, _super);
  35400. /**
  35401. * Instantiates a ColorGradingTexture from the following parameters.
  35402. *
  35403. * @param url The location of the color gradind data (currently only supporting 3dl)
  35404. * @param scene The scene the texture will be used in
  35405. */
  35406. function ColorGradingTexture(url, scene) {
  35407. var _this = _super.call(this, scene) || this;
  35408. if (!url) {
  35409. return _this;
  35410. }
  35411. _this._engine = scene.getEngine();
  35412. _this._textureMatrix = BABYLON.Matrix.Identity();
  35413. _this.name = url;
  35414. _this.url = url;
  35415. _this.hasAlpha = false;
  35416. _this.isCube = false;
  35417. _this.is3D = _this._engine.webGLVersion > 1;
  35418. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35419. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35420. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35421. _this.anisotropicFilteringLevel = 1;
  35422. _this._texture = _this._getFromCache(url, true);
  35423. if (!_this._texture) {
  35424. if (!scene.useDelayedTextureLoading) {
  35425. _this.loadTexture();
  35426. }
  35427. else {
  35428. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35429. }
  35430. }
  35431. return _this;
  35432. }
  35433. /**
  35434. * Returns the texture matrix used in most of the material.
  35435. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35436. */
  35437. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35438. return this._textureMatrix;
  35439. };
  35440. /**
  35441. * Occurs when the file being loaded is a .3dl LUT file.
  35442. */
  35443. ColorGradingTexture.prototype.load3dlTexture = function () {
  35444. var engine = this._engine;
  35445. var texture;
  35446. if (engine.webGLVersion === 1) {
  35447. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35448. }
  35449. else {
  35450. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35451. }
  35452. this._texture = texture;
  35453. var callback = function (text) {
  35454. if (typeof text !== "string") {
  35455. return;
  35456. }
  35457. var data = null;
  35458. var tempData = null;
  35459. var line;
  35460. var lines = text.split('\n');
  35461. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35462. var maxColor = 0;
  35463. for (var i = 0; i < lines.length; i++) {
  35464. line = lines[i];
  35465. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35466. continue;
  35467. if (line.indexOf('#') === 0)
  35468. continue;
  35469. var words = line.split(" ");
  35470. if (size === 0) {
  35471. // Number of space + one
  35472. size = words.length;
  35473. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35474. tempData = new Float32Array(size * size * size * 4);
  35475. continue;
  35476. }
  35477. if (size != 0) {
  35478. var r = Math.max(parseInt(words[0]), 0);
  35479. var g = Math.max(parseInt(words[1]), 0);
  35480. var b = Math.max(parseInt(words[2]), 0);
  35481. maxColor = Math.max(r, maxColor);
  35482. maxColor = Math.max(g, maxColor);
  35483. maxColor = Math.max(b, maxColor);
  35484. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35485. if (tempData) {
  35486. tempData[pixelStorageIndex + 0] = r;
  35487. tempData[pixelStorageIndex + 1] = g;
  35488. tempData[pixelStorageIndex + 2] = b;
  35489. }
  35490. pixelIndexSlice++;
  35491. if (pixelIndexSlice % size == 0) {
  35492. pixelIndexH++;
  35493. pixelIndexSlice = 0;
  35494. if (pixelIndexH % size == 0) {
  35495. pixelIndexW++;
  35496. pixelIndexH = 0;
  35497. }
  35498. }
  35499. }
  35500. }
  35501. if (tempData && data) {
  35502. for (var i = 0; i < tempData.length; i++) {
  35503. if (i > 0 && (i + 1) % 4 === 0) {
  35504. data[i] = 255;
  35505. }
  35506. else {
  35507. var value = tempData[i];
  35508. data[i] = (value / maxColor * 255);
  35509. }
  35510. }
  35511. }
  35512. if (texture.is3D) {
  35513. texture.updateSize(size, size, size);
  35514. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35515. }
  35516. else {
  35517. texture.updateSize(size * size, size);
  35518. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35519. }
  35520. };
  35521. var scene = this.getScene();
  35522. if (scene) {
  35523. scene._loadFile(this.url, callback);
  35524. }
  35525. else {
  35526. this._engine._loadFile(this.url, callback);
  35527. }
  35528. return this._texture;
  35529. };
  35530. /**
  35531. * Starts the loading process of the texture.
  35532. */
  35533. ColorGradingTexture.prototype.loadTexture = function () {
  35534. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35535. this.load3dlTexture();
  35536. }
  35537. };
  35538. /**
  35539. * Clones the color gradind texture.
  35540. */
  35541. ColorGradingTexture.prototype.clone = function () {
  35542. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35543. // Base texture
  35544. newTexture.level = this.level;
  35545. return newTexture;
  35546. };
  35547. /**
  35548. * Called during delayed load for textures.
  35549. */
  35550. ColorGradingTexture.prototype.delayLoad = function () {
  35551. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35552. return;
  35553. }
  35554. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35555. this._texture = this._getFromCache(this.url, true);
  35556. if (!this._texture) {
  35557. this.loadTexture();
  35558. }
  35559. };
  35560. /**
  35561. * Parses a color grading texture serialized by Babylon.
  35562. * @param parsedTexture The texture information being parsedTexture
  35563. * @param scene The scene to load the texture in
  35564. * @param rootUrl The root url of the data assets to load
  35565. * @return A color gradind texture
  35566. */
  35567. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35568. var texture = null;
  35569. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35570. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35571. texture.name = parsedTexture.name;
  35572. texture.level = parsedTexture.level;
  35573. }
  35574. return texture;
  35575. };
  35576. /**
  35577. * Serializes the LUT texture to json format.
  35578. */
  35579. ColorGradingTexture.prototype.serialize = function () {
  35580. if (!this.name) {
  35581. return null;
  35582. }
  35583. var serializationObject = {};
  35584. serializationObject.name = this.name;
  35585. serializationObject.level = this.level;
  35586. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35587. return serializationObject;
  35588. };
  35589. /**
  35590. * Empty line regex stored for GC.
  35591. */
  35592. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35593. return ColorGradingTexture;
  35594. }(BABYLON.BaseTexture));
  35595. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35596. })(BABYLON || (BABYLON = {}));
  35597. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35598. var BABYLON;
  35599. (function (BABYLON) {
  35600. /**
  35601. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35602. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35603. * 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;
  35604. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35605. */
  35606. var ColorCurves = /** @class */ (function () {
  35607. function ColorCurves() {
  35608. this._dirty = true;
  35609. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35610. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35611. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35612. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35613. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35614. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35615. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35616. this._globalHue = 30;
  35617. this._globalDensity = 0;
  35618. this._globalSaturation = 0;
  35619. this._globalExposure = 0;
  35620. this._highlightsHue = 30;
  35621. this._highlightsDensity = 0;
  35622. this._highlightsSaturation = 0;
  35623. this._highlightsExposure = 0;
  35624. this._midtonesHue = 30;
  35625. this._midtonesDensity = 0;
  35626. this._midtonesSaturation = 0;
  35627. this._midtonesExposure = 0;
  35628. this._shadowsHue = 30;
  35629. this._shadowsDensity = 0;
  35630. this._shadowsSaturation = 0;
  35631. this._shadowsExposure = 0;
  35632. }
  35633. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35634. /**
  35635. * Gets the global Hue value.
  35636. * 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).
  35637. */
  35638. get: function () {
  35639. return this._globalHue;
  35640. },
  35641. /**
  35642. * Sets the global Hue value.
  35643. * 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).
  35644. */
  35645. set: function (value) {
  35646. this._globalHue = value;
  35647. this._dirty = true;
  35648. },
  35649. enumerable: true,
  35650. configurable: true
  35651. });
  35652. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35653. /**
  35654. * Gets the global Density value.
  35655. * 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.
  35656. * Values less than zero provide a filter of opposite hue.
  35657. */
  35658. get: function () {
  35659. return this._globalDensity;
  35660. },
  35661. /**
  35662. * Sets the global Density value.
  35663. * 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.
  35664. * Values less than zero provide a filter of opposite hue.
  35665. */
  35666. set: function (value) {
  35667. this._globalDensity = value;
  35668. this._dirty = true;
  35669. },
  35670. enumerable: true,
  35671. configurable: true
  35672. });
  35673. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35674. /**
  35675. * Gets the global Saturation value.
  35676. * 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.
  35677. */
  35678. get: function () {
  35679. return this._globalSaturation;
  35680. },
  35681. /**
  35682. * Sets the global Saturation value.
  35683. * 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.
  35684. */
  35685. set: function (value) {
  35686. this._globalSaturation = value;
  35687. this._dirty = true;
  35688. },
  35689. enumerable: true,
  35690. configurable: true
  35691. });
  35692. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35693. /**
  35694. * Gets the highlights Hue value.
  35695. * 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).
  35696. */
  35697. get: function () {
  35698. return this._highlightsHue;
  35699. },
  35700. /**
  35701. * Sets the highlights Hue value.
  35702. * 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).
  35703. */
  35704. set: function (value) {
  35705. this._highlightsHue = value;
  35706. this._dirty = true;
  35707. },
  35708. enumerable: true,
  35709. configurable: true
  35710. });
  35711. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35712. /**
  35713. * Gets the highlights Density value.
  35714. * 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.
  35715. * Values less than zero provide a filter of opposite hue.
  35716. */
  35717. get: function () {
  35718. return this._highlightsDensity;
  35719. },
  35720. /**
  35721. * Sets the highlights Density value.
  35722. * 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.
  35723. * Values less than zero provide a filter of opposite hue.
  35724. */
  35725. set: function (value) {
  35726. this._highlightsDensity = value;
  35727. this._dirty = true;
  35728. },
  35729. enumerable: true,
  35730. configurable: true
  35731. });
  35732. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35733. /**
  35734. * Gets the highlights Saturation value.
  35735. * 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.
  35736. */
  35737. get: function () {
  35738. return this._highlightsSaturation;
  35739. },
  35740. /**
  35741. * Sets the highlights Saturation value.
  35742. * 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.
  35743. */
  35744. set: function (value) {
  35745. this._highlightsSaturation = value;
  35746. this._dirty = true;
  35747. },
  35748. enumerable: true,
  35749. configurable: true
  35750. });
  35751. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35752. /**
  35753. * Gets the highlights Exposure value.
  35754. * 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.
  35755. */
  35756. get: function () {
  35757. return this._highlightsExposure;
  35758. },
  35759. /**
  35760. * Sets the highlights Exposure value.
  35761. * 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.
  35762. */
  35763. set: function (value) {
  35764. this._highlightsExposure = value;
  35765. this._dirty = true;
  35766. },
  35767. enumerable: true,
  35768. configurable: true
  35769. });
  35770. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35771. /**
  35772. * Gets the midtones Hue value.
  35773. * 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).
  35774. */
  35775. get: function () {
  35776. return this._midtonesHue;
  35777. },
  35778. /**
  35779. * Sets the midtones Hue value.
  35780. * 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).
  35781. */
  35782. set: function (value) {
  35783. this._midtonesHue = value;
  35784. this._dirty = true;
  35785. },
  35786. enumerable: true,
  35787. configurable: true
  35788. });
  35789. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35790. /**
  35791. * Gets the midtones Density value.
  35792. * 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.
  35793. * Values less than zero provide a filter of opposite hue.
  35794. */
  35795. get: function () {
  35796. return this._midtonesDensity;
  35797. },
  35798. /**
  35799. * Sets the midtones Density value.
  35800. * 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.
  35801. * Values less than zero provide a filter of opposite hue.
  35802. */
  35803. set: function (value) {
  35804. this._midtonesDensity = value;
  35805. this._dirty = true;
  35806. },
  35807. enumerable: true,
  35808. configurable: true
  35809. });
  35810. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35811. /**
  35812. * Gets the midtones Saturation value.
  35813. * 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.
  35814. */
  35815. get: function () {
  35816. return this._midtonesSaturation;
  35817. },
  35818. /**
  35819. * Sets the midtones Saturation value.
  35820. * 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.
  35821. */
  35822. set: function (value) {
  35823. this._midtonesSaturation = value;
  35824. this._dirty = true;
  35825. },
  35826. enumerable: true,
  35827. configurable: true
  35828. });
  35829. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35830. /**
  35831. * Gets the midtones Exposure value.
  35832. * 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.
  35833. */
  35834. get: function () {
  35835. return this._midtonesExposure;
  35836. },
  35837. /**
  35838. * Sets the midtones Exposure value.
  35839. * 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.
  35840. */
  35841. set: function (value) {
  35842. this._midtonesExposure = value;
  35843. this._dirty = true;
  35844. },
  35845. enumerable: true,
  35846. configurable: true
  35847. });
  35848. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35849. /**
  35850. * Gets the shadows Hue value.
  35851. * 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).
  35852. */
  35853. get: function () {
  35854. return this._shadowsHue;
  35855. },
  35856. /**
  35857. * Sets the shadows Hue value.
  35858. * 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).
  35859. */
  35860. set: function (value) {
  35861. this._shadowsHue = value;
  35862. this._dirty = true;
  35863. },
  35864. enumerable: true,
  35865. configurable: true
  35866. });
  35867. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35868. /**
  35869. * Gets the shadows Density value.
  35870. * 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.
  35871. * Values less than zero provide a filter of opposite hue.
  35872. */
  35873. get: function () {
  35874. return this._shadowsDensity;
  35875. },
  35876. /**
  35877. * Sets the shadows Density value.
  35878. * 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.
  35879. * Values less than zero provide a filter of opposite hue.
  35880. */
  35881. set: function (value) {
  35882. this._shadowsDensity = value;
  35883. this._dirty = true;
  35884. },
  35885. enumerable: true,
  35886. configurable: true
  35887. });
  35888. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35889. /**
  35890. * Gets the shadows Saturation value.
  35891. * 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.
  35892. */
  35893. get: function () {
  35894. return this._shadowsSaturation;
  35895. },
  35896. /**
  35897. * Sets the shadows Saturation value.
  35898. * 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.
  35899. */
  35900. set: function (value) {
  35901. this._shadowsSaturation = value;
  35902. this._dirty = true;
  35903. },
  35904. enumerable: true,
  35905. configurable: true
  35906. });
  35907. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35908. /**
  35909. * Gets the shadows Exposure value.
  35910. * 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.
  35911. */
  35912. get: function () {
  35913. return this._shadowsExposure;
  35914. },
  35915. /**
  35916. * Sets the shadows Exposure value.
  35917. * 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.
  35918. */
  35919. set: function (value) {
  35920. this._shadowsExposure = value;
  35921. this._dirty = true;
  35922. },
  35923. enumerable: true,
  35924. configurable: true
  35925. });
  35926. ColorCurves.prototype.getClassName = function () {
  35927. return "ColorCurves";
  35928. };
  35929. /**
  35930. * Binds the color curves to the shader.
  35931. * @param colorCurves The color curve to bind
  35932. * @param effect The effect to bind to
  35933. */
  35934. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35935. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35936. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35937. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35938. if (colorCurves._dirty) {
  35939. colorCurves._dirty = false;
  35940. // Fill in global info.
  35941. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35942. // Compute highlights info.
  35943. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35944. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35945. // Compute midtones info.
  35946. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35947. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35948. // Compute shadows info.
  35949. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35950. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35951. // Compute deltas (neutral is midtones).
  35952. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35953. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35954. }
  35955. if (effect) {
  35956. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35957. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35958. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35959. }
  35960. };
  35961. /**
  35962. * Prepare the list of uniforms associated with the ColorCurves effects.
  35963. * @param uniformsList The list of uniforms used in the effect
  35964. */
  35965. ColorCurves.PrepareUniforms = function (uniformsList) {
  35966. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35967. };
  35968. /**
  35969. * Returns color grading data based on a hue, density, saturation and exposure value.
  35970. * @param filterHue The hue of the color filter.
  35971. * @param filterDensity The density of the color filter.
  35972. * @param saturation The saturation.
  35973. * @param exposure The exposure.
  35974. * @param result The result data container.
  35975. */
  35976. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35977. if (hue == null) {
  35978. return;
  35979. }
  35980. hue = ColorCurves.clamp(hue, 0, 360);
  35981. density = ColorCurves.clamp(density, -100, 100);
  35982. saturation = ColorCurves.clamp(saturation, -100, 100);
  35983. exposure = ColorCurves.clamp(exposure, -100, 100);
  35984. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35985. // so that the maximum filter density is only 50% control. This provides fine control
  35986. // for small values and reasonable range.
  35987. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35988. density *= 0.5;
  35989. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35990. if (density < 0) {
  35991. density *= -1;
  35992. hue = (hue + 180) % 360;
  35993. }
  35994. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35995. result.scaleToRef(2, result);
  35996. result.a = 1 + 0.01 * saturation;
  35997. };
  35998. /**
  35999. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  36000. * @param value The input slider value in range [-100,100].
  36001. * @returns Adjusted value.
  36002. */
  36003. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  36004. value /= 100;
  36005. var x = Math.abs(value);
  36006. x = Math.pow(x, 2);
  36007. if (value < 0) {
  36008. x *= -1;
  36009. }
  36010. x *= 100;
  36011. return x;
  36012. };
  36013. /**
  36014. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  36015. * @param hue The hue (H) input.
  36016. * @param saturation The saturation (S) input.
  36017. * @param brightness The brightness (B) input.
  36018. * @result An RGBA color represented as Vector4.
  36019. */
  36020. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  36021. var h = ColorCurves.clamp(hue, 0, 360);
  36022. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  36023. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  36024. if (s === 0) {
  36025. result.r = v;
  36026. result.g = v;
  36027. result.b = v;
  36028. }
  36029. else {
  36030. // sector 0 to 5
  36031. h /= 60;
  36032. var i = Math.floor(h);
  36033. // fractional part of h
  36034. var f = h - i;
  36035. var p = v * (1 - s);
  36036. var q = v * (1 - s * f);
  36037. var t = v * (1 - s * (1 - f));
  36038. switch (i) {
  36039. case 0:
  36040. result.r = v;
  36041. result.g = t;
  36042. result.b = p;
  36043. break;
  36044. case 1:
  36045. result.r = q;
  36046. result.g = v;
  36047. result.b = p;
  36048. break;
  36049. case 2:
  36050. result.r = p;
  36051. result.g = v;
  36052. result.b = t;
  36053. break;
  36054. case 3:
  36055. result.r = p;
  36056. result.g = q;
  36057. result.b = v;
  36058. break;
  36059. case 4:
  36060. result.r = t;
  36061. result.g = p;
  36062. result.b = v;
  36063. break;
  36064. default:// case 5:
  36065. result.r = v;
  36066. result.g = p;
  36067. result.b = q;
  36068. break;
  36069. }
  36070. }
  36071. result.a = 1;
  36072. };
  36073. /**
  36074. * Returns a value clamped between min and max
  36075. * @param value The value to clamp
  36076. * @param min The minimum of value
  36077. * @param max The maximum of value
  36078. * @returns The clamped value.
  36079. */
  36080. ColorCurves.clamp = function (value, min, max) {
  36081. return Math.min(Math.max(value, min), max);
  36082. };
  36083. /**
  36084. * Clones the current color curve instance.
  36085. * @return The cloned curves
  36086. */
  36087. ColorCurves.prototype.clone = function () {
  36088. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  36089. };
  36090. /**
  36091. * Serializes the current color curve instance to a json representation.
  36092. * @return a JSON representation
  36093. */
  36094. ColorCurves.prototype.serialize = function () {
  36095. return BABYLON.SerializationHelper.Serialize(this);
  36096. };
  36097. /**
  36098. * Parses the color curve from a json representation.
  36099. * @param source the JSON source to parse
  36100. * @return The parsed curves
  36101. */
  36102. ColorCurves.Parse = function (source) {
  36103. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  36104. };
  36105. __decorate([
  36106. BABYLON.serialize()
  36107. ], ColorCurves.prototype, "_globalHue", void 0);
  36108. __decorate([
  36109. BABYLON.serialize()
  36110. ], ColorCurves.prototype, "_globalDensity", void 0);
  36111. __decorate([
  36112. BABYLON.serialize()
  36113. ], ColorCurves.prototype, "_globalSaturation", void 0);
  36114. __decorate([
  36115. BABYLON.serialize()
  36116. ], ColorCurves.prototype, "_globalExposure", void 0);
  36117. __decorate([
  36118. BABYLON.serialize()
  36119. ], ColorCurves.prototype, "_highlightsHue", void 0);
  36120. __decorate([
  36121. BABYLON.serialize()
  36122. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  36123. __decorate([
  36124. BABYLON.serialize()
  36125. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  36126. __decorate([
  36127. BABYLON.serialize()
  36128. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  36129. __decorate([
  36130. BABYLON.serialize()
  36131. ], ColorCurves.prototype, "_midtonesHue", void 0);
  36132. __decorate([
  36133. BABYLON.serialize()
  36134. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  36135. __decorate([
  36136. BABYLON.serialize()
  36137. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  36138. __decorate([
  36139. BABYLON.serialize()
  36140. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36141. return ColorCurves;
  36142. }());
  36143. BABYLON.ColorCurves = ColorCurves;
  36144. })(BABYLON || (BABYLON = {}));
  36145. //# sourceMappingURL=babylon.colorCurves.js.map
  36146. //# sourceMappingURL=babylon.behavior.js.map
  36147. var BABYLON;
  36148. (function (BABYLON) {
  36149. /**
  36150. * "Static Class" containing the most commonly used helper while dealing with material for
  36151. * rendering purpose.
  36152. *
  36153. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  36154. *
  36155. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  36156. */
  36157. var MaterialHelper = /** @class */ (function () {
  36158. function MaterialHelper() {
  36159. }
  36160. /**
  36161. * Bind the current view position to an effect.
  36162. * @param effect The effect to be bound
  36163. * @param scene The scene the eyes position is used from
  36164. */
  36165. MaterialHelper.BindEyePosition = function (effect, scene) {
  36166. if (scene._forcedViewPosition) {
  36167. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36168. return;
  36169. }
  36170. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36171. };
  36172. /**
  36173. * Helps preparing the defines values about the UVs in used in the effect.
  36174. * UVs are shared as much as we can accross chanels in the shaders.
  36175. * @param texture The texture we are preparing the UVs for
  36176. * @param defines The defines to update
  36177. * @param key The chanel key "diffuse", "specular"... used in the shader
  36178. */
  36179. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36180. defines._needUVs = true;
  36181. defines[key] = true;
  36182. if (texture.getTextureMatrix().isIdentity(true)) {
  36183. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36184. if (texture.coordinatesIndex === 0) {
  36185. defines["MAINUV1"] = true;
  36186. }
  36187. else {
  36188. defines["MAINUV2"] = true;
  36189. }
  36190. }
  36191. else {
  36192. defines[key + "DIRECTUV"] = 0;
  36193. }
  36194. };
  36195. /**
  36196. * Binds a texture matrix value to its corrsponding uniform
  36197. * @param texture The texture to bind the matrix for
  36198. * @param uniformBuffer The uniform buffer receivin the data
  36199. * @param key The chanel key "diffuse", "specular"... used in the shader
  36200. */
  36201. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36202. var matrix = texture.getTextureMatrix();
  36203. if (!matrix.isIdentity(true)) {
  36204. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36205. }
  36206. };
  36207. /**
  36208. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36209. * @param mesh defines the current mesh
  36210. * @param scene defines the current scene
  36211. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36212. * @param pointsCloud defines if point cloud rendering has to be turned on
  36213. * @param fogEnabled defines if fog has to be turned on
  36214. * @param alphaTest defines if alpha testing has to be turned on
  36215. * @param defines defines the current list of defines
  36216. */
  36217. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36218. if (defines._areMiscDirty) {
  36219. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36220. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36221. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36222. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36223. defines["ALPHATEST"] = alphaTest;
  36224. }
  36225. };
  36226. /**
  36227. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36228. * @param scene defines the current scene
  36229. * @param engine defines the current engine
  36230. * @param defines specifies the list of active defines
  36231. * @param useInstances defines if instances have to be turned on
  36232. */
  36233. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36234. var changed = false;
  36235. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36236. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36237. changed = true;
  36238. }
  36239. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36240. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36241. changed = true;
  36242. }
  36243. if (defines["INSTANCES"] !== useInstances) {
  36244. defines["INSTANCES"] = useInstances;
  36245. changed = true;
  36246. }
  36247. if (changed) {
  36248. defines.markAsUnprocessed();
  36249. }
  36250. };
  36251. /**
  36252. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  36253. * @param mesh The mesh containing the geometry data we will draw
  36254. * @param defines The defines to update
  36255. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  36256. * @param useBones Precise whether bones should be used or not (override mesh info)
  36257. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  36258. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  36259. * @returns false if defines are considered not dirty and have not been checked
  36260. */
  36261. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36262. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36263. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36264. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36265. return false;
  36266. }
  36267. defines._normals = defines._needNormals;
  36268. defines._uvs = defines._needUVs;
  36269. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36270. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36271. defines["TANGENT"] = true;
  36272. }
  36273. if (defines._needUVs) {
  36274. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36275. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36276. }
  36277. else {
  36278. defines["UV1"] = false;
  36279. defines["UV2"] = false;
  36280. }
  36281. if (useVertexColor) {
  36282. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36283. defines["VERTEXCOLOR"] = hasVertexColors;
  36284. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36285. }
  36286. if (useBones) {
  36287. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36288. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36289. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36290. }
  36291. else {
  36292. defines["NUM_BONE_INFLUENCERS"] = 0;
  36293. defines["BonesPerMesh"] = 0;
  36294. }
  36295. }
  36296. if (useMorphTargets) {
  36297. var manager = mesh.morphTargetManager;
  36298. if (manager) {
  36299. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36300. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36301. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36302. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36303. }
  36304. else {
  36305. defines["MORPHTARGETS_TANGENT"] = false;
  36306. defines["MORPHTARGETS_NORMAL"] = false;
  36307. defines["MORPHTARGETS"] = false;
  36308. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36309. }
  36310. }
  36311. return true;
  36312. };
  36313. /**
  36314. * Prepares the defines related to the light information passed in parameter
  36315. * @param scene The scene we are intending to draw
  36316. * @param mesh The mesh the effect is compiling for
  36317. * @param defines The defines to update
  36318. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  36319. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  36320. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  36321. * @returns true if normals will be required for the rest of the effect
  36322. */
  36323. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36324. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36325. if (disableLighting === void 0) { disableLighting = false; }
  36326. if (!defines._areLightsDirty) {
  36327. return defines._needNormals;
  36328. }
  36329. var lightIndex = 0;
  36330. var needNormals = false;
  36331. var needRebuild = false;
  36332. var lightmapMode = false;
  36333. var shadowEnabled = false;
  36334. var specularEnabled = false;
  36335. if (scene.lightsEnabled && !disableLighting) {
  36336. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36337. var light = _a[_i];
  36338. needNormals = true;
  36339. if (defines["LIGHT" + lightIndex] === undefined) {
  36340. needRebuild = true;
  36341. }
  36342. defines["LIGHT" + lightIndex] = true;
  36343. defines["SPOTLIGHT" + lightIndex] = false;
  36344. defines["HEMILIGHT" + lightIndex] = false;
  36345. defines["POINTLIGHT" + lightIndex] = false;
  36346. defines["DIRLIGHT" + lightIndex] = false;
  36347. var type;
  36348. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36349. type = "SPOTLIGHT" + lightIndex;
  36350. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = light.projectedLightTexture ? true : false;
  36351. }
  36352. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36353. type = "HEMILIGHT" + lightIndex;
  36354. }
  36355. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36356. type = "POINTLIGHT" + lightIndex;
  36357. }
  36358. else {
  36359. type = "DIRLIGHT" + lightIndex;
  36360. }
  36361. defines[type] = true;
  36362. // Specular
  36363. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36364. specularEnabled = true;
  36365. }
  36366. // Shadows
  36367. defines["SHADOW" + lightIndex] = false;
  36368. defines["SHADOWPCF" + lightIndex] = false;
  36369. defines["SHADOWESM" + lightIndex] = false;
  36370. defines["SHADOWCUBE" + lightIndex] = false;
  36371. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36372. var shadowGenerator = light.getShadowGenerator();
  36373. if (shadowGenerator) {
  36374. shadowEnabled = true;
  36375. shadowGenerator.prepareDefines(defines, lightIndex);
  36376. }
  36377. }
  36378. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36379. lightmapMode = true;
  36380. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36381. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36382. }
  36383. else {
  36384. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36385. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36386. }
  36387. lightIndex++;
  36388. if (lightIndex === maxSimultaneousLights)
  36389. break;
  36390. }
  36391. }
  36392. defines["SPECULARTERM"] = specularEnabled;
  36393. defines["SHADOWS"] = shadowEnabled;
  36394. // Resetting all other lights if any
  36395. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36396. if (defines["LIGHT" + index] !== undefined) {
  36397. defines["LIGHT" + index] = false;
  36398. defines["HEMILIGHT" + lightIndex] = false;
  36399. defines["POINTLIGHT" + lightIndex] = false;
  36400. defines["DIRLIGHT" + lightIndex] = false;
  36401. defines["SPOTLIGHT" + lightIndex] = false;
  36402. defines["SHADOW" + lightIndex] = false;
  36403. }
  36404. }
  36405. var caps = scene.getEngine().getCaps();
  36406. if (defines["SHADOWFLOAT"] === undefined) {
  36407. needRebuild = true;
  36408. }
  36409. defines["SHADOWFLOAT"] = shadowEnabled &&
  36410. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36411. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36412. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36413. if (needRebuild) {
  36414. defines.rebuild();
  36415. }
  36416. return needNormals;
  36417. };
  36418. /**
  36419. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  36420. * that won t be acctive due to defines being turned off.
  36421. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  36422. * @param samplersList The samplers list
  36423. * @param defines The defines helping in the list generation
  36424. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  36425. */
  36426. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36427. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36428. var uniformsList;
  36429. var uniformBuffersList = null;
  36430. if (uniformsListOrOptions.uniformsNames) {
  36431. var options = uniformsListOrOptions;
  36432. uniformsList = options.uniformsNames;
  36433. uniformBuffersList = options.uniformBuffersNames;
  36434. samplersList = options.samplers;
  36435. defines = options.defines;
  36436. maxSimultaneousLights = options.maxSimultaneousLights;
  36437. }
  36438. else {
  36439. uniformsList = uniformsListOrOptions;
  36440. if (!samplersList) {
  36441. samplersList = [];
  36442. }
  36443. }
  36444. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36445. if (!defines["LIGHT" + lightIndex]) {
  36446. break;
  36447. }
  36448. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36449. if (uniformBuffersList) {
  36450. uniformBuffersList.push("Light" + lightIndex);
  36451. }
  36452. samplersList.push("shadowSampler" + lightIndex);
  36453. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  36454. samplersList.push("projectionLightSampler" + lightIndex);
  36455. uniformsList.push("textureProjectionMatrix" + lightIndex);
  36456. }
  36457. }
  36458. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36459. uniformsList.push("morphTargetInfluences");
  36460. }
  36461. };
  36462. /**
  36463. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  36464. * @param defines The defines to update while falling back
  36465. * @param fallbacks The authorized effect fallbacks
  36466. * @param maxSimultaneousLights The maximum number of lights allowed
  36467. * @param rank the current rank of the Effect
  36468. * @returns The newly affected rank
  36469. */
  36470. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36471. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36472. if (rank === void 0) { rank = 0; }
  36473. var lightFallbackRank = 0;
  36474. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36475. if (!defines["LIGHT" + lightIndex]) {
  36476. break;
  36477. }
  36478. if (lightIndex > 0) {
  36479. lightFallbackRank = rank + lightIndex;
  36480. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36481. }
  36482. if (!defines["SHADOWS"]) {
  36483. if (defines["SHADOW" + lightIndex]) {
  36484. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36485. }
  36486. if (defines["SHADOWPCF" + lightIndex]) {
  36487. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36488. }
  36489. if (defines["SHADOWESM" + lightIndex]) {
  36490. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36491. }
  36492. }
  36493. }
  36494. return lightFallbackRank++;
  36495. };
  36496. /**
  36497. * Prepares the list of attributes required for morph targets according to the effect defines.
  36498. * @param attribs The current list of supported attribs
  36499. * @param mesh The mesh to prepare the morph targets attributes for
  36500. * @param defines The current Defines of the effect
  36501. */
  36502. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36503. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36504. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36505. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36506. var manager = mesh.morphTargetManager;
  36507. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36508. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36509. for (var index = 0; index < influencers; index++) {
  36510. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36511. if (normal) {
  36512. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36513. }
  36514. if (tangent) {
  36515. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36516. }
  36517. if (attribs.length > maxAttributesCount) {
  36518. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36519. }
  36520. }
  36521. }
  36522. };
  36523. /**
  36524. * Prepares the list of attributes required for bones according to the effect defines.
  36525. * @param attribs The current list of supported attribs
  36526. * @param mesh The mesh to prepare the bones attributes for
  36527. * @param defines The current Defines of the effect
  36528. * @param fallbacks The current efffect fallback strategy
  36529. */
  36530. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36531. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36532. fallbacks.addCPUSkinningFallback(0, mesh);
  36533. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36534. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36535. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36538. }
  36539. }
  36540. };
  36541. /**
  36542. * Prepares the list of attributes required for instances according to the effect defines.
  36543. * @param attribs The current list of supported attribs
  36544. * @param defines The current Defines of the effect
  36545. */
  36546. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36547. if (defines["INSTANCES"]) {
  36548. attribs.push("world0");
  36549. attribs.push("world1");
  36550. attribs.push("world2");
  36551. attribs.push("world3");
  36552. }
  36553. };
  36554. /**
  36555. * Binds the light shadow information to the effect for the given mesh.
  36556. * @param light The light containing the generator
  36557. * @param scene The scene the lights belongs to
  36558. * @param mesh The mesh we are binding the information to render
  36559. * @param lightIndex The light index in the effect used to render the mesh
  36560. * @param effect The effect we are binding the data to
  36561. */
  36562. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36563. if (light.shadowEnabled && mesh.receiveShadows) {
  36564. var shadowGenerator = light.getShadowGenerator();
  36565. if (shadowGenerator) {
  36566. shadowGenerator.bindShadowLight(lightIndex, effect);
  36567. }
  36568. }
  36569. };
  36570. /**
  36571. * Binds the light information to the effect.
  36572. * @param light The light containing the generator
  36573. * @param effect The effect we are binding the data to
  36574. * @param lightIndex The light index in the effect used to render
  36575. */
  36576. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36577. light.transferToEffect(effect, lightIndex + "");
  36578. };
  36579. /**
  36580. * Binds the lights information from the scene to the effect for the given mesh.
  36581. * @param scene The scene the lights belongs to
  36582. * @param mesh The mesh we are binding the information to render
  36583. * @param effect The effect we are binding the data to
  36584. * @param defines The generated defines for the effect
  36585. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  36586. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  36587. */
  36588. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36589. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36590. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36591. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36592. for (var i = 0; i < len; i++) {
  36593. var light = mesh._lightSources[i];
  36594. var iAsString = i.toString();
  36595. var scaledIntensity = light.getScaledIntensity();
  36596. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36597. MaterialHelper.BindLightProperties(light, effect, i);
  36598. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36599. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36600. if (defines["SPECULARTERM"]) {
  36601. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36602. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36603. }
  36604. // Shadows
  36605. if (scene.shadowsEnabled) {
  36606. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36607. }
  36608. light._uniformBuffer.update();
  36609. }
  36610. };
  36611. /**
  36612. * Binds the fog information from the scene to the effect for the given mesh.
  36613. * @param scene The scene the lights belongs to
  36614. * @param mesh The mesh we are binding the information to render
  36615. * @param effect The effect we are binding the data to
  36616. */
  36617. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36618. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36619. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36620. effect.setColor3("vFogColor", scene.fogColor);
  36621. }
  36622. };
  36623. /**
  36624. * Binds the bones information from the mesh to the effect.
  36625. * @param mesh The mesh we are binding the information to render
  36626. * @param effect The effect we are binding the data to
  36627. */
  36628. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36629. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36630. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36631. if (matrices && effect) {
  36632. effect.setMatrices("mBones", matrices);
  36633. }
  36634. }
  36635. };
  36636. /**
  36637. * Binds the morph targets information from the mesh to the effect.
  36638. * @param abstractMesh The mesh we are binding the information to render
  36639. * @param effect The effect we are binding the data to
  36640. */
  36641. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36642. var manager = abstractMesh.morphTargetManager;
  36643. if (!abstractMesh || !manager) {
  36644. return;
  36645. }
  36646. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36647. };
  36648. /**
  36649. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  36650. * @param defines The generated defines used in the effect
  36651. * @param effect The effect we are binding the data to
  36652. * @param scene The scene we are willing to render with logarithmic scale for
  36653. */
  36654. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36655. if (defines["LOGARITHMICDEPTH"]) {
  36656. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36657. }
  36658. };
  36659. /**
  36660. * Binds the clip plane information from the scene to the effect.
  36661. * @param scene The scene the clip plane information are extracted from
  36662. * @param effect The effect we are binding the data to
  36663. */
  36664. MaterialHelper.BindClipPlane = function (effect, scene) {
  36665. if (scene.clipPlane) {
  36666. var clipPlane = scene.clipPlane;
  36667. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36668. }
  36669. };
  36670. return MaterialHelper;
  36671. }());
  36672. BABYLON.MaterialHelper = MaterialHelper;
  36673. })(BABYLON || (BABYLON = {}));
  36674. //# sourceMappingURL=babylon.materialHelper.js.map
  36675. var BABYLON;
  36676. (function (BABYLON) {
  36677. var PushMaterial = /** @class */ (function (_super) {
  36678. __extends(PushMaterial, _super);
  36679. function PushMaterial(name, scene) {
  36680. var _this = _super.call(this, name, scene) || this;
  36681. _this.storeEffectOnSubMeshes = true;
  36682. return _this;
  36683. }
  36684. PushMaterial.prototype.getEffect = function () {
  36685. return this._activeEffect;
  36686. };
  36687. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36688. if (!mesh) {
  36689. return false;
  36690. }
  36691. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36692. return true;
  36693. }
  36694. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36695. };
  36696. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36697. this._activeEffect.setMatrix("world", world);
  36698. };
  36699. PushMaterial.prototype.bind = function (world, mesh) {
  36700. if (!mesh) {
  36701. return;
  36702. }
  36703. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36704. };
  36705. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36706. if (effect === void 0) { effect = null; }
  36707. _super.prototype._afterBind.call(this, mesh);
  36708. this.getScene()._cachedEffect = effect;
  36709. };
  36710. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36711. if (visibility === void 0) { visibility = 1; }
  36712. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36713. };
  36714. return PushMaterial;
  36715. }(BABYLON.Material));
  36716. BABYLON.PushMaterial = PushMaterial;
  36717. })(BABYLON || (BABYLON = {}));
  36718. //# sourceMappingURL=babylon.pushMaterial.js.map
  36719. var BABYLON;
  36720. (function (BABYLON) {
  36721. var StandardMaterialDefines = /** @class */ (function (_super) {
  36722. __extends(StandardMaterialDefines, _super);
  36723. function StandardMaterialDefines() {
  36724. var _this = _super.call(this) || this;
  36725. _this.MAINUV1 = false;
  36726. _this.MAINUV2 = false;
  36727. _this.DIFFUSE = false;
  36728. _this.DIFFUSEDIRECTUV = 0;
  36729. _this.AMBIENT = false;
  36730. _this.AMBIENTDIRECTUV = 0;
  36731. _this.OPACITY = false;
  36732. _this.OPACITYDIRECTUV = 0;
  36733. _this.OPACITYRGB = false;
  36734. _this.REFLECTION = false;
  36735. _this.EMISSIVE = false;
  36736. _this.EMISSIVEDIRECTUV = 0;
  36737. _this.SPECULAR = false;
  36738. _this.SPECULARDIRECTUV = 0;
  36739. _this.BUMP = false;
  36740. _this.BUMPDIRECTUV = 0;
  36741. _this.PARALLAX = false;
  36742. _this.PARALLAXOCCLUSION = false;
  36743. _this.SPECULAROVERALPHA = false;
  36744. _this.CLIPPLANE = false;
  36745. _this.ALPHATEST = false;
  36746. _this.DEPTHPREPASS = false;
  36747. _this.ALPHAFROMDIFFUSE = false;
  36748. _this.POINTSIZE = false;
  36749. _this.FOG = false;
  36750. _this.SPECULARTERM = false;
  36751. _this.DIFFUSEFRESNEL = false;
  36752. _this.OPACITYFRESNEL = false;
  36753. _this.REFLECTIONFRESNEL = false;
  36754. _this.REFRACTIONFRESNEL = false;
  36755. _this.EMISSIVEFRESNEL = false;
  36756. _this.FRESNEL = false;
  36757. _this.NORMAL = false;
  36758. _this.UV1 = false;
  36759. _this.UV2 = false;
  36760. _this.VERTEXCOLOR = false;
  36761. _this.VERTEXALPHA = false;
  36762. _this.NUM_BONE_INFLUENCERS = 0;
  36763. _this.BonesPerMesh = 0;
  36764. _this.INSTANCES = false;
  36765. _this.GLOSSINESS = false;
  36766. _this.ROUGHNESS = false;
  36767. _this.EMISSIVEASILLUMINATION = false;
  36768. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36769. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36770. _this.LIGHTMAP = false;
  36771. _this.LIGHTMAPDIRECTUV = 0;
  36772. _this.USELIGHTMAPASSHADOWMAP = false;
  36773. _this.REFLECTIONMAP_3D = false;
  36774. _this.REFLECTIONMAP_SPHERICAL = false;
  36775. _this.REFLECTIONMAP_PLANAR = false;
  36776. _this.REFLECTIONMAP_CUBIC = false;
  36777. _this.REFLECTIONMAP_PROJECTION = false;
  36778. _this.REFLECTIONMAP_SKYBOX = false;
  36779. _this.REFLECTIONMAP_EXPLICIT = false;
  36780. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36781. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36782. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36783. _this.INVERTCUBICMAP = false;
  36784. _this.LOGARITHMICDEPTH = false;
  36785. _this.REFRACTION = false;
  36786. _this.REFRACTIONMAP_3D = false;
  36787. _this.REFLECTIONOVERALPHA = false;
  36788. _this.TWOSIDEDLIGHTING = false;
  36789. _this.SHADOWFLOAT = false;
  36790. _this.MORPHTARGETS = false;
  36791. _this.MORPHTARGETS_NORMAL = false;
  36792. _this.MORPHTARGETS_TANGENT = false;
  36793. _this.NUM_MORPH_INFLUENCERS = 0;
  36794. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36795. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36796. _this.IMAGEPROCESSING = false;
  36797. _this.VIGNETTE = false;
  36798. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36799. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36800. _this.TONEMAPPING = false;
  36801. _this.CONTRAST = false;
  36802. _this.COLORCURVES = false;
  36803. _this.COLORGRADING = false;
  36804. _this.COLORGRADING3D = false;
  36805. _this.SAMPLER3DGREENDEPTH = false;
  36806. _this.SAMPLER3DBGRMAP = false;
  36807. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36808. _this.EXPOSURE = false;
  36809. _this.rebuild();
  36810. return _this;
  36811. }
  36812. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36813. var modes = [
  36814. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36815. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36816. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36817. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36818. ];
  36819. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36820. var mode = modes_1[_i];
  36821. this[mode] = (mode === modeToEnable);
  36822. }
  36823. };
  36824. return StandardMaterialDefines;
  36825. }(BABYLON.MaterialDefines));
  36826. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36827. var StandardMaterial = /** @class */ (function (_super) {
  36828. __extends(StandardMaterial, _super);
  36829. function StandardMaterial(name, scene) {
  36830. var _this = _super.call(this, name, scene) || this;
  36831. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36832. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36833. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36834. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36835. _this.specularPower = 64;
  36836. _this._useAlphaFromDiffuseTexture = false;
  36837. _this._useEmissiveAsIllumination = false;
  36838. _this._linkEmissiveWithDiffuse = false;
  36839. _this._useSpecularOverAlpha = false;
  36840. _this._useReflectionOverAlpha = false;
  36841. _this._disableLighting = false;
  36842. _this._useParallax = false;
  36843. _this._useParallaxOcclusion = false;
  36844. _this.parallaxScaleBias = 0.05;
  36845. _this._roughness = 0;
  36846. _this.indexOfRefraction = 0.98;
  36847. _this.invertRefractionY = true;
  36848. _this._useLightmapAsShadowmap = false;
  36849. _this._useReflectionFresnelFromSpecular = false;
  36850. _this._useGlossinessFromSpecularMapAlpha = false;
  36851. _this._maxSimultaneousLights = 4;
  36852. /**
  36853. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36854. */
  36855. _this._invertNormalMapX = false;
  36856. /**
  36857. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36858. */
  36859. _this._invertNormalMapY = false;
  36860. /**
  36861. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36862. */
  36863. _this._twoSidedLighting = false;
  36864. _this._renderTargets = new BABYLON.SmartArray(16);
  36865. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36866. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36867. // Setup the default processing configuration to the scene.
  36868. _this._attachImageProcessingConfiguration(null);
  36869. _this.getRenderTargetTextures = function () {
  36870. _this._renderTargets.reset();
  36871. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36872. _this._renderTargets.push(_this._reflectionTexture);
  36873. }
  36874. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36875. _this._renderTargets.push(_this._refractionTexture);
  36876. }
  36877. return _this._renderTargets;
  36878. };
  36879. return _this;
  36880. }
  36881. ;
  36882. ;
  36883. ;
  36884. ;
  36885. ;
  36886. ;
  36887. ;
  36888. ;
  36889. ;
  36890. ;
  36891. ;
  36892. ;
  36893. ;
  36894. ;
  36895. ;
  36896. ;
  36897. ;
  36898. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36899. /**
  36900. * Gets the image processing configuration used either in this material.
  36901. */
  36902. get: function () {
  36903. return this._imageProcessingConfiguration;
  36904. },
  36905. /**
  36906. * Sets the Default image processing configuration used either in the this material.
  36907. *
  36908. * If sets to null, the scene one is in use.
  36909. */
  36910. set: function (value) {
  36911. this._attachImageProcessingConfiguration(value);
  36912. // Ensure the effect will be rebuilt.
  36913. this._markAllSubMeshesAsTexturesDirty();
  36914. },
  36915. enumerable: true,
  36916. configurable: true
  36917. });
  36918. /**
  36919. * Attaches a new image processing configuration to the Standard Material.
  36920. * @param configuration
  36921. */
  36922. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36923. var _this = this;
  36924. if (configuration === this._imageProcessingConfiguration) {
  36925. return;
  36926. }
  36927. // Detaches observer.
  36928. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36929. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36930. }
  36931. // Pick the scene configuration if needed.
  36932. if (!configuration) {
  36933. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36934. }
  36935. else {
  36936. this._imageProcessingConfiguration = configuration;
  36937. }
  36938. // Attaches observer.
  36939. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36940. _this._markAllSubMeshesAsImageProcessingDirty();
  36941. });
  36942. };
  36943. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36944. /**
  36945. * Gets wether the color curves effect is enabled.
  36946. */
  36947. get: function () {
  36948. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36949. },
  36950. /**
  36951. * Sets wether the color curves effect is enabled.
  36952. */
  36953. set: function (value) {
  36954. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36955. },
  36956. enumerable: true,
  36957. configurable: true
  36958. });
  36959. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36960. /**
  36961. * Gets wether the color grading effect is enabled.
  36962. */
  36963. get: function () {
  36964. return this.imageProcessingConfiguration.colorGradingEnabled;
  36965. },
  36966. /**
  36967. * Gets wether the color grading effect is enabled.
  36968. */
  36969. set: function (value) {
  36970. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36971. },
  36972. enumerable: true,
  36973. configurable: true
  36974. });
  36975. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36976. /**
  36977. * Gets wether tonemapping is enabled or not.
  36978. */
  36979. get: function () {
  36980. return this._imageProcessingConfiguration.toneMappingEnabled;
  36981. },
  36982. /**
  36983. * Sets wether tonemapping is enabled or not
  36984. */
  36985. set: function (value) {
  36986. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36987. },
  36988. enumerable: true,
  36989. configurable: true
  36990. });
  36991. ;
  36992. ;
  36993. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36994. /**
  36995. * The camera exposure used on this material.
  36996. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36997. * This corresponds to a photographic exposure.
  36998. */
  36999. get: function () {
  37000. return this._imageProcessingConfiguration.exposure;
  37001. },
  37002. /**
  37003. * The camera exposure used on this material.
  37004. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37005. * This corresponds to a photographic exposure.
  37006. */
  37007. set: function (value) {
  37008. this._imageProcessingConfiguration.exposure = value;
  37009. },
  37010. enumerable: true,
  37011. configurable: true
  37012. });
  37013. ;
  37014. ;
  37015. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  37016. /**
  37017. * Gets The camera contrast used on this material.
  37018. */
  37019. get: function () {
  37020. return this._imageProcessingConfiguration.contrast;
  37021. },
  37022. /**
  37023. * Sets The camera contrast used on this material.
  37024. */
  37025. set: function (value) {
  37026. this._imageProcessingConfiguration.contrast = value;
  37027. },
  37028. enumerable: true,
  37029. configurable: true
  37030. });
  37031. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  37032. /**
  37033. * Gets the Color Grading 2D Lookup Texture.
  37034. */
  37035. get: function () {
  37036. return this._imageProcessingConfiguration.colorGradingTexture;
  37037. },
  37038. /**
  37039. * Sets the Color Grading 2D Lookup Texture.
  37040. */
  37041. set: function (value) {
  37042. this._imageProcessingConfiguration.colorGradingTexture = value;
  37043. },
  37044. enumerable: true,
  37045. configurable: true
  37046. });
  37047. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  37048. /**
  37049. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37050. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37051. * 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;
  37052. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37053. */
  37054. get: function () {
  37055. return this._imageProcessingConfiguration.colorCurves;
  37056. },
  37057. /**
  37058. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37059. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37060. * 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;
  37061. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37062. */
  37063. set: function (value) {
  37064. this._imageProcessingConfiguration.colorCurves = value;
  37065. },
  37066. enumerable: true,
  37067. configurable: true
  37068. });
  37069. StandardMaterial.prototype.getClassName = function () {
  37070. return "StandardMaterial";
  37071. };
  37072. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  37073. get: function () {
  37074. return this._useLogarithmicDepth;
  37075. },
  37076. set: function (value) {
  37077. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37078. this._markAllSubMeshesAsMiscDirty();
  37079. },
  37080. enumerable: true,
  37081. configurable: true
  37082. });
  37083. StandardMaterial.prototype.needAlphaBlending = function () {
  37084. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  37085. };
  37086. StandardMaterial.prototype.needAlphaTesting = function () {
  37087. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  37088. };
  37089. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  37090. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  37091. };
  37092. StandardMaterial.prototype.getAlphaTestTexture = function () {
  37093. return this._diffuseTexture;
  37094. };
  37095. /**
  37096. * Child classes can use it to update shaders
  37097. */
  37098. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37099. if (useInstances === void 0) { useInstances = false; }
  37100. if (subMesh.effect && this.isFrozen) {
  37101. if (this._wasPreviouslyReady && subMesh.effect) {
  37102. return true;
  37103. }
  37104. }
  37105. if (!subMesh._materialDefines) {
  37106. subMesh._materialDefines = new StandardMaterialDefines();
  37107. }
  37108. var scene = this.getScene();
  37109. var defines = subMesh._materialDefines;
  37110. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37111. if (defines._renderId === scene.getRenderId()) {
  37112. return true;
  37113. }
  37114. }
  37115. var engine = scene.getEngine();
  37116. // Lights
  37117. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37118. // Textures
  37119. if (defines._areTexturesDirty) {
  37120. defines._needUVs = false;
  37121. defines.MAINUV1 = false;
  37122. defines.MAINUV2 = false;
  37123. if (scene.texturesEnabled) {
  37124. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37125. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  37126. return false;
  37127. }
  37128. else {
  37129. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  37130. }
  37131. }
  37132. else {
  37133. defines.DIFFUSE = false;
  37134. }
  37135. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37136. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37137. return false;
  37138. }
  37139. else {
  37140. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37141. }
  37142. }
  37143. else {
  37144. defines.AMBIENT = false;
  37145. }
  37146. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37147. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37148. return false;
  37149. }
  37150. else {
  37151. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37152. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37153. }
  37154. }
  37155. else {
  37156. defines.OPACITY = false;
  37157. }
  37158. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37159. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  37160. return false;
  37161. }
  37162. else {
  37163. defines._needNormals = true;
  37164. defines.REFLECTION = true;
  37165. defines.ROUGHNESS = (this._roughness > 0);
  37166. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  37167. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  37168. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  37169. switch (this._reflectionTexture.coordinatesMode) {
  37170. case BABYLON.Texture.CUBIC_MODE:
  37171. case BABYLON.Texture.INVCUBIC_MODE:
  37172. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  37173. break;
  37174. case BABYLON.Texture.EXPLICIT_MODE:
  37175. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  37176. break;
  37177. case BABYLON.Texture.PLANAR_MODE:
  37178. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  37179. break;
  37180. case BABYLON.Texture.PROJECTION_MODE:
  37181. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  37182. break;
  37183. case BABYLON.Texture.SKYBOX_MODE:
  37184. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  37185. break;
  37186. case BABYLON.Texture.SPHERICAL_MODE:
  37187. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  37188. break;
  37189. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37190. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  37191. break;
  37192. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37193. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  37194. break;
  37195. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37196. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  37197. break;
  37198. }
  37199. }
  37200. }
  37201. else {
  37202. defines.REFLECTION = false;
  37203. }
  37204. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37205. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37206. return false;
  37207. }
  37208. else {
  37209. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37210. }
  37211. }
  37212. else {
  37213. defines.EMISSIVE = false;
  37214. }
  37215. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37216. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37217. return false;
  37218. }
  37219. else {
  37220. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37221. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37222. }
  37223. }
  37224. else {
  37225. defines.LIGHTMAP = false;
  37226. }
  37227. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37228. if (!this._specularTexture.isReadyOrNotBlocking()) {
  37229. return false;
  37230. }
  37231. else {
  37232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  37233. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  37234. }
  37235. }
  37236. else {
  37237. defines.SPECULAR = false;
  37238. }
  37239. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  37240. // Bump texure can not be not blocking.
  37241. if (!this._bumpTexture.isReady()) {
  37242. return false;
  37243. }
  37244. else {
  37245. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37246. defines.PARALLAX = this._useParallax;
  37247. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  37248. }
  37249. }
  37250. else {
  37251. defines.BUMP = false;
  37252. }
  37253. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37254. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  37255. return false;
  37256. }
  37257. else {
  37258. defines._needUVs = true;
  37259. defines.REFRACTION = true;
  37260. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  37261. }
  37262. }
  37263. else {
  37264. defines.REFRACTION = false;
  37265. }
  37266. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  37267. }
  37268. else {
  37269. defines.DIFFUSE = false;
  37270. defines.AMBIENT = false;
  37271. defines.OPACITY = false;
  37272. defines.REFLECTION = false;
  37273. defines.EMISSIVE = false;
  37274. defines.LIGHTMAP = false;
  37275. defines.BUMP = false;
  37276. defines.REFRACTION = false;
  37277. }
  37278. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37279. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37280. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37281. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37282. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37283. }
  37284. if (defines._areImageProcessingDirty) {
  37285. if (!this._imageProcessingConfiguration.isReady()) {
  37286. return false;
  37287. }
  37288. this._imageProcessingConfiguration.prepareDefines(defines);
  37289. }
  37290. if (defines._areFresnelDirty) {
  37291. if (StandardMaterial.FresnelEnabled) {
  37292. // Fresnel
  37293. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37294. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37295. this._reflectionFresnelParameters) {
  37296. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37297. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37298. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37299. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37300. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37301. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37302. defines._needNormals = true;
  37303. defines.FRESNEL = true;
  37304. }
  37305. }
  37306. else {
  37307. defines.FRESNEL = false;
  37308. }
  37309. }
  37310. // Misc.
  37311. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37312. // Attribs
  37313. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37314. // Values that need to be evaluated on every frame
  37315. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37316. // Get correct effect
  37317. if (defines.isDirty) {
  37318. defines.markAsProcessed();
  37319. scene.resetCachedMaterial();
  37320. // Fallbacks
  37321. var fallbacks = new BABYLON.EffectFallbacks();
  37322. if (defines.REFLECTION) {
  37323. fallbacks.addFallback(0, "REFLECTION");
  37324. }
  37325. if (defines.SPECULAR) {
  37326. fallbacks.addFallback(0, "SPECULAR");
  37327. }
  37328. if (defines.BUMP) {
  37329. fallbacks.addFallback(0, "BUMP");
  37330. }
  37331. if (defines.PARALLAX) {
  37332. fallbacks.addFallback(1, "PARALLAX");
  37333. }
  37334. if (defines.PARALLAXOCCLUSION) {
  37335. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37336. }
  37337. if (defines.SPECULAROVERALPHA) {
  37338. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37339. }
  37340. if (defines.FOG) {
  37341. fallbacks.addFallback(1, "FOG");
  37342. }
  37343. if (defines.POINTSIZE) {
  37344. fallbacks.addFallback(0, "POINTSIZE");
  37345. }
  37346. if (defines.LOGARITHMICDEPTH) {
  37347. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37348. }
  37349. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37350. if (defines.SPECULARTERM) {
  37351. fallbacks.addFallback(0, "SPECULARTERM");
  37352. }
  37353. if (defines.DIFFUSEFRESNEL) {
  37354. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37355. }
  37356. if (defines.OPACITYFRESNEL) {
  37357. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37358. }
  37359. if (defines.REFLECTIONFRESNEL) {
  37360. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37361. }
  37362. if (defines.EMISSIVEFRESNEL) {
  37363. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37364. }
  37365. if (defines.FRESNEL) {
  37366. fallbacks.addFallback(4, "FRESNEL");
  37367. }
  37368. //Attributes
  37369. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37370. if (defines.NORMAL) {
  37371. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37372. }
  37373. if (defines.UV1) {
  37374. attribs.push(BABYLON.VertexBuffer.UVKind);
  37375. }
  37376. if (defines.UV2) {
  37377. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37378. }
  37379. if (defines.VERTEXCOLOR) {
  37380. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37381. }
  37382. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37383. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37384. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37385. var shaderName = "default";
  37386. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37387. "vFogInfos", "vFogColor", "pointSize",
  37388. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37389. "mBones",
  37390. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37391. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37392. "logarithmicDepthConstant", "vTangentSpaceParams"
  37393. ];
  37394. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37395. var uniformBuffers = ["Material", "Scene"];
  37396. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37397. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37398. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37399. uniformsNames: uniforms,
  37400. uniformBuffersNames: uniformBuffers,
  37401. samplers: samplers,
  37402. defines: defines,
  37403. maxSimultaneousLights: this._maxSimultaneousLights
  37404. });
  37405. if (this.customShaderNameResolve) {
  37406. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37407. }
  37408. var join = defines.toString();
  37409. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37410. attributes: attribs,
  37411. uniformsNames: uniforms,
  37412. uniformBuffersNames: uniformBuffers,
  37413. samplers: samplers,
  37414. defines: join,
  37415. fallbacks: fallbacks,
  37416. onCompiled: this.onCompiled,
  37417. onError: this.onError,
  37418. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37419. }, engine), defines);
  37420. this.buildUniformLayout();
  37421. }
  37422. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37423. return false;
  37424. }
  37425. defines._renderId = scene.getRenderId();
  37426. this._wasPreviouslyReady = true;
  37427. return true;
  37428. };
  37429. StandardMaterial.prototype.buildUniformLayout = function () {
  37430. // Order is important !
  37431. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37432. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37433. this._uniformBuffer.addUniform("opacityParts", 4);
  37434. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37435. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37436. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37437. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37438. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37439. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37440. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37441. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37442. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37443. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37444. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37445. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37446. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37447. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37448. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37449. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37450. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37451. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37452. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37453. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37454. this._uniformBuffer.addUniform("specularMatrix", 16);
  37455. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37456. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37457. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37458. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37459. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37460. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37461. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37462. this._uniformBuffer.addUniform("pointSize", 1);
  37463. this._uniformBuffer.create();
  37464. };
  37465. StandardMaterial.prototype.unbind = function () {
  37466. if (this._activeEffect) {
  37467. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37468. this._activeEffect.setTexture("reflection2DSampler", null);
  37469. }
  37470. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37471. this._activeEffect.setTexture("refraction2DSampler", null);
  37472. }
  37473. }
  37474. _super.prototype.unbind.call(this);
  37475. };
  37476. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37477. var scene = this.getScene();
  37478. var defines = subMesh._materialDefines;
  37479. if (!defines) {
  37480. return;
  37481. }
  37482. var effect = subMesh.effect;
  37483. if (!effect) {
  37484. return;
  37485. }
  37486. this._activeEffect = effect;
  37487. // Matrices
  37488. this.bindOnlyWorldMatrix(world);
  37489. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37490. // Bones
  37491. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37492. if (mustRebind) {
  37493. this._uniformBuffer.bindToEffect(effect, "Material");
  37494. this.bindViewProjection(effect);
  37495. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37496. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37497. // Fresnel
  37498. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37499. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37500. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37501. }
  37502. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37503. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37504. }
  37505. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37506. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37507. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37508. }
  37509. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37510. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37511. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37512. }
  37513. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37514. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37515. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37516. }
  37517. }
  37518. // Textures
  37519. if (scene.texturesEnabled) {
  37520. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37521. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37522. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37523. }
  37524. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37525. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37526. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37527. }
  37528. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37529. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37530. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37531. }
  37532. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37533. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37534. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37535. }
  37536. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37537. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37538. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37539. }
  37540. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37541. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37542. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37543. }
  37544. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37545. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37546. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37547. }
  37548. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37549. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37550. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37551. if (scene._mirroredCameraPosition) {
  37552. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37553. }
  37554. else {
  37555. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37556. }
  37557. }
  37558. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37559. var depth = 1.0;
  37560. if (!this._refractionTexture.isCube) {
  37561. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37562. if (this._refractionTexture.depth) {
  37563. depth = this._refractionTexture.depth;
  37564. }
  37565. }
  37566. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37567. }
  37568. }
  37569. // Point size
  37570. if (this.pointsCloud) {
  37571. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37572. }
  37573. if (defines.SPECULARTERM) {
  37574. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37575. }
  37576. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37577. // Diffuse
  37578. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37579. }
  37580. // Textures
  37581. if (scene.texturesEnabled) {
  37582. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37583. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37584. }
  37585. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37586. effect.setTexture("ambientSampler", this._ambientTexture);
  37587. }
  37588. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37589. effect.setTexture("opacitySampler", this._opacityTexture);
  37590. }
  37591. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37592. if (this._reflectionTexture.isCube) {
  37593. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37594. }
  37595. else {
  37596. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37597. }
  37598. }
  37599. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37600. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37601. }
  37602. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37603. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37604. }
  37605. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37606. effect.setTexture("specularSampler", this._specularTexture);
  37607. }
  37608. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37609. effect.setTexture("bumpSampler", this._bumpTexture);
  37610. }
  37611. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37612. var depth = 1.0;
  37613. if (this._refractionTexture.isCube) {
  37614. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37615. }
  37616. else {
  37617. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37618. }
  37619. }
  37620. }
  37621. // Clip plane
  37622. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37623. // Colors
  37624. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37625. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37626. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37627. }
  37628. if (mustRebind || !this.isFrozen) {
  37629. // Lights
  37630. if (scene.lightsEnabled && !this._disableLighting) {
  37631. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37632. }
  37633. // View
  37634. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37635. this.bindView(effect);
  37636. }
  37637. // Fog
  37638. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37639. // Morph targets
  37640. if (defines.NUM_MORPH_INFLUENCERS) {
  37641. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37642. }
  37643. // Log. depth
  37644. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37645. // image processing
  37646. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37647. this._imageProcessingConfiguration.bind(this._activeEffect);
  37648. }
  37649. }
  37650. this._uniformBuffer.update();
  37651. this._afterBind(mesh, this._activeEffect);
  37652. };
  37653. StandardMaterial.prototype.getAnimatables = function () {
  37654. var results = [];
  37655. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37656. results.push(this._diffuseTexture);
  37657. }
  37658. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37659. results.push(this._ambientTexture);
  37660. }
  37661. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37662. results.push(this._opacityTexture);
  37663. }
  37664. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37665. results.push(this._reflectionTexture);
  37666. }
  37667. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37668. results.push(this._emissiveTexture);
  37669. }
  37670. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37671. results.push(this._specularTexture);
  37672. }
  37673. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37674. results.push(this._bumpTexture);
  37675. }
  37676. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37677. results.push(this._lightmapTexture);
  37678. }
  37679. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37680. results.push(this._refractionTexture);
  37681. }
  37682. return results;
  37683. };
  37684. StandardMaterial.prototype.getActiveTextures = function () {
  37685. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37686. if (this._diffuseTexture) {
  37687. activeTextures.push(this._diffuseTexture);
  37688. }
  37689. if (this._ambientTexture) {
  37690. activeTextures.push(this._ambientTexture);
  37691. }
  37692. if (this._opacityTexture) {
  37693. activeTextures.push(this._opacityTexture);
  37694. }
  37695. if (this._reflectionTexture) {
  37696. activeTextures.push(this._reflectionTexture);
  37697. }
  37698. if (this._emissiveTexture) {
  37699. activeTextures.push(this._emissiveTexture);
  37700. }
  37701. if (this._specularTexture) {
  37702. activeTextures.push(this._specularTexture);
  37703. }
  37704. if (this._bumpTexture) {
  37705. activeTextures.push(this._bumpTexture);
  37706. }
  37707. if (this._lightmapTexture) {
  37708. activeTextures.push(this._lightmapTexture);
  37709. }
  37710. if (this._refractionTexture) {
  37711. activeTextures.push(this._refractionTexture);
  37712. }
  37713. return activeTextures;
  37714. };
  37715. StandardMaterial.prototype.hasTexture = function (texture) {
  37716. if (_super.prototype.hasTexture.call(this, texture)) {
  37717. return true;
  37718. }
  37719. if (this._diffuseTexture === texture) {
  37720. return true;
  37721. }
  37722. if (this._ambientTexture === texture) {
  37723. return true;
  37724. }
  37725. if (this._opacityTexture === texture) {
  37726. return true;
  37727. }
  37728. if (this._reflectionTexture === texture) {
  37729. return true;
  37730. }
  37731. if (this._emissiveTexture === texture) {
  37732. return true;
  37733. }
  37734. if (this._specularTexture === texture) {
  37735. return true;
  37736. }
  37737. if (this._bumpTexture === texture) {
  37738. return true;
  37739. }
  37740. if (this._lightmapTexture === texture) {
  37741. return true;
  37742. }
  37743. if (this._refractionTexture === texture) {
  37744. return true;
  37745. }
  37746. return false;
  37747. };
  37748. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37749. if (forceDisposeTextures) {
  37750. if (this._diffuseTexture) {
  37751. this._diffuseTexture.dispose();
  37752. }
  37753. if (this._ambientTexture) {
  37754. this._ambientTexture.dispose();
  37755. }
  37756. if (this._opacityTexture) {
  37757. this._opacityTexture.dispose();
  37758. }
  37759. if (this._reflectionTexture) {
  37760. this._reflectionTexture.dispose();
  37761. }
  37762. if (this._emissiveTexture) {
  37763. this._emissiveTexture.dispose();
  37764. }
  37765. if (this._specularTexture) {
  37766. this._specularTexture.dispose();
  37767. }
  37768. if (this._bumpTexture) {
  37769. this._bumpTexture.dispose();
  37770. }
  37771. if (this._lightmapTexture) {
  37772. this._lightmapTexture.dispose();
  37773. }
  37774. if (this._refractionTexture) {
  37775. this._refractionTexture.dispose();
  37776. }
  37777. }
  37778. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37779. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37780. }
  37781. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37782. };
  37783. StandardMaterial.prototype.clone = function (name) {
  37784. var _this = this;
  37785. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37786. result.name = name;
  37787. result.id = name;
  37788. return result;
  37789. };
  37790. StandardMaterial.prototype.serialize = function () {
  37791. return BABYLON.SerializationHelper.Serialize(this);
  37792. };
  37793. // Statics
  37794. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37795. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37796. };
  37797. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37798. get: function () {
  37799. return StandardMaterial._DiffuseTextureEnabled;
  37800. },
  37801. set: function (value) {
  37802. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37803. return;
  37804. }
  37805. StandardMaterial._DiffuseTextureEnabled = value;
  37806. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37807. },
  37808. enumerable: true,
  37809. configurable: true
  37810. });
  37811. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37812. get: function () {
  37813. return StandardMaterial._AmbientTextureEnabled;
  37814. },
  37815. set: function (value) {
  37816. if (StandardMaterial._AmbientTextureEnabled === value) {
  37817. return;
  37818. }
  37819. StandardMaterial._AmbientTextureEnabled = value;
  37820. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37821. },
  37822. enumerable: true,
  37823. configurable: true
  37824. });
  37825. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37826. get: function () {
  37827. return StandardMaterial._OpacityTextureEnabled;
  37828. },
  37829. set: function (value) {
  37830. if (StandardMaterial._OpacityTextureEnabled === value) {
  37831. return;
  37832. }
  37833. StandardMaterial._OpacityTextureEnabled = value;
  37834. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37835. },
  37836. enumerable: true,
  37837. configurable: true
  37838. });
  37839. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37840. get: function () {
  37841. return StandardMaterial._ReflectionTextureEnabled;
  37842. },
  37843. set: function (value) {
  37844. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37845. return;
  37846. }
  37847. StandardMaterial._ReflectionTextureEnabled = value;
  37848. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37849. },
  37850. enumerable: true,
  37851. configurable: true
  37852. });
  37853. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37854. get: function () {
  37855. return StandardMaterial._EmissiveTextureEnabled;
  37856. },
  37857. set: function (value) {
  37858. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37859. return;
  37860. }
  37861. StandardMaterial._EmissiveTextureEnabled = value;
  37862. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37863. },
  37864. enumerable: true,
  37865. configurable: true
  37866. });
  37867. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37868. get: function () {
  37869. return StandardMaterial._SpecularTextureEnabled;
  37870. },
  37871. set: function (value) {
  37872. if (StandardMaterial._SpecularTextureEnabled === value) {
  37873. return;
  37874. }
  37875. StandardMaterial._SpecularTextureEnabled = value;
  37876. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37877. },
  37878. enumerable: true,
  37879. configurable: true
  37880. });
  37881. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37882. get: function () {
  37883. return StandardMaterial._BumpTextureEnabled;
  37884. },
  37885. set: function (value) {
  37886. if (StandardMaterial._BumpTextureEnabled === value) {
  37887. return;
  37888. }
  37889. StandardMaterial._BumpTextureEnabled = value;
  37890. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37891. },
  37892. enumerable: true,
  37893. configurable: true
  37894. });
  37895. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37896. get: function () {
  37897. return StandardMaterial._LightmapTextureEnabled;
  37898. },
  37899. set: function (value) {
  37900. if (StandardMaterial._LightmapTextureEnabled === value) {
  37901. return;
  37902. }
  37903. StandardMaterial._LightmapTextureEnabled = value;
  37904. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37905. },
  37906. enumerable: true,
  37907. configurable: true
  37908. });
  37909. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37910. get: function () {
  37911. return StandardMaterial._RefractionTextureEnabled;
  37912. },
  37913. set: function (value) {
  37914. if (StandardMaterial._RefractionTextureEnabled === value) {
  37915. return;
  37916. }
  37917. StandardMaterial._RefractionTextureEnabled = value;
  37918. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37919. },
  37920. enumerable: true,
  37921. configurable: true
  37922. });
  37923. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37924. get: function () {
  37925. return StandardMaterial._ColorGradingTextureEnabled;
  37926. },
  37927. set: function (value) {
  37928. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37929. return;
  37930. }
  37931. StandardMaterial._ColorGradingTextureEnabled = value;
  37932. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37933. },
  37934. enumerable: true,
  37935. configurable: true
  37936. });
  37937. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37938. get: function () {
  37939. return StandardMaterial._FresnelEnabled;
  37940. },
  37941. set: function (value) {
  37942. if (StandardMaterial._FresnelEnabled === value) {
  37943. return;
  37944. }
  37945. StandardMaterial._FresnelEnabled = value;
  37946. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37947. },
  37948. enumerable: true,
  37949. configurable: true
  37950. });
  37951. // Flags used to enable or disable a type of texture for all Standard Materials
  37952. StandardMaterial._DiffuseTextureEnabled = true;
  37953. StandardMaterial._AmbientTextureEnabled = true;
  37954. StandardMaterial._OpacityTextureEnabled = true;
  37955. StandardMaterial._ReflectionTextureEnabled = true;
  37956. StandardMaterial._EmissiveTextureEnabled = true;
  37957. StandardMaterial._SpecularTextureEnabled = true;
  37958. StandardMaterial._BumpTextureEnabled = true;
  37959. StandardMaterial._LightmapTextureEnabled = true;
  37960. StandardMaterial._RefractionTextureEnabled = true;
  37961. StandardMaterial._ColorGradingTextureEnabled = true;
  37962. StandardMaterial._FresnelEnabled = true;
  37963. __decorate([
  37964. BABYLON.serializeAsTexture("diffuseTexture")
  37965. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37966. __decorate([
  37967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37968. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37969. __decorate([
  37970. BABYLON.serializeAsTexture("ambientTexture")
  37971. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37972. __decorate([
  37973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37974. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37975. __decorate([
  37976. BABYLON.serializeAsTexture("opacityTexture")
  37977. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37978. __decorate([
  37979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37980. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37981. __decorate([
  37982. BABYLON.serializeAsTexture("reflectionTexture")
  37983. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37984. __decorate([
  37985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37986. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37987. __decorate([
  37988. BABYLON.serializeAsTexture("emissiveTexture")
  37989. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37990. __decorate([
  37991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37992. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37993. __decorate([
  37994. BABYLON.serializeAsTexture("specularTexture")
  37995. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37996. __decorate([
  37997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37998. ], StandardMaterial.prototype, "specularTexture", void 0);
  37999. __decorate([
  38000. BABYLON.serializeAsTexture("bumpTexture")
  38001. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  38002. __decorate([
  38003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38004. ], StandardMaterial.prototype, "bumpTexture", void 0);
  38005. __decorate([
  38006. BABYLON.serializeAsTexture("lightmapTexture")
  38007. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  38008. __decorate([
  38009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38010. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  38011. __decorate([
  38012. BABYLON.serializeAsTexture("refractionTexture")
  38013. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  38014. __decorate([
  38015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38016. ], StandardMaterial.prototype, "refractionTexture", void 0);
  38017. __decorate([
  38018. BABYLON.serializeAsColor3("ambient")
  38019. ], StandardMaterial.prototype, "ambientColor", void 0);
  38020. __decorate([
  38021. BABYLON.serializeAsColor3("diffuse")
  38022. ], StandardMaterial.prototype, "diffuseColor", void 0);
  38023. __decorate([
  38024. BABYLON.serializeAsColor3("specular")
  38025. ], StandardMaterial.prototype, "specularColor", void 0);
  38026. __decorate([
  38027. BABYLON.serializeAsColor3("emissive")
  38028. ], StandardMaterial.prototype, "emissiveColor", void 0);
  38029. __decorate([
  38030. BABYLON.serialize()
  38031. ], StandardMaterial.prototype, "specularPower", void 0);
  38032. __decorate([
  38033. BABYLON.serialize("useAlphaFromDiffuseTexture")
  38034. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  38035. __decorate([
  38036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38037. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  38038. __decorate([
  38039. BABYLON.serialize("useEmissiveAsIllumination")
  38040. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  38041. __decorate([
  38042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38043. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  38044. __decorate([
  38045. BABYLON.serialize("linkEmissiveWithDiffuse")
  38046. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  38047. __decorate([
  38048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38049. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  38050. __decorate([
  38051. BABYLON.serialize("useSpecularOverAlpha")
  38052. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  38053. __decorate([
  38054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38055. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  38056. __decorate([
  38057. BABYLON.serialize("useReflectionOverAlpha")
  38058. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  38059. __decorate([
  38060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38061. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  38062. __decorate([
  38063. BABYLON.serialize("disableLighting")
  38064. ], StandardMaterial.prototype, "_disableLighting", void 0);
  38065. __decorate([
  38066. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38067. ], StandardMaterial.prototype, "disableLighting", void 0);
  38068. __decorate([
  38069. BABYLON.serialize("useParallax")
  38070. ], StandardMaterial.prototype, "_useParallax", void 0);
  38071. __decorate([
  38072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38073. ], StandardMaterial.prototype, "useParallax", void 0);
  38074. __decorate([
  38075. BABYLON.serialize("useParallaxOcclusion")
  38076. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  38077. __decorate([
  38078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38079. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  38080. __decorate([
  38081. BABYLON.serialize()
  38082. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  38083. __decorate([
  38084. BABYLON.serialize("roughness")
  38085. ], StandardMaterial.prototype, "_roughness", void 0);
  38086. __decorate([
  38087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38088. ], StandardMaterial.prototype, "roughness", void 0);
  38089. __decorate([
  38090. BABYLON.serialize()
  38091. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  38092. __decorate([
  38093. BABYLON.serialize()
  38094. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  38095. __decorate([
  38096. BABYLON.serialize("useLightmapAsShadowmap")
  38097. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  38098. __decorate([
  38099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38100. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38101. __decorate([
  38102. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  38103. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  38104. __decorate([
  38105. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38106. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  38107. __decorate([
  38108. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  38109. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  38110. __decorate([
  38111. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  38112. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  38113. __decorate([
  38114. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  38115. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  38116. __decorate([
  38117. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38118. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  38119. __decorate([
  38120. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  38121. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  38122. __decorate([
  38123. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38124. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  38125. __decorate([
  38126. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  38127. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  38128. __decorate([
  38129. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38130. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  38131. __decorate([
  38132. BABYLON.serialize("useReflectionFresnelFromSpecular")
  38133. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  38134. __decorate([
  38135. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38136. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  38137. __decorate([
  38138. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  38139. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  38140. __decorate([
  38141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38142. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  38143. __decorate([
  38144. BABYLON.serialize("maxSimultaneousLights")
  38145. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  38146. __decorate([
  38147. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38148. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  38149. __decorate([
  38150. BABYLON.serialize("invertNormalMapX")
  38151. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  38152. __decorate([
  38153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38154. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  38155. __decorate([
  38156. BABYLON.serialize("invertNormalMapY")
  38157. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  38158. __decorate([
  38159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38160. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  38161. __decorate([
  38162. BABYLON.serialize("twoSidedLighting")
  38163. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  38164. __decorate([
  38165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38166. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  38167. __decorate([
  38168. BABYLON.serialize()
  38169. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  38170. return StandardMaterial;
  38171. }(BABYLON.PushMaterial));
  38172. BABYLON.StandardMaterial = StandardMaterial;
  38173. })(BABYLON || (BABYLON = {}));
  38174. //# sourceMappingURL=babylon.standardMaterial.js.map
  38175. var BABYLON;
  38176. (function (BABYLON) {
  38177. var PBRMaterialDefines = /** @class */ (function (_super) {
  38178. __extends(PBRMaterialDefines, _super);
  38179. function PBRMaterialDefines() {
  38180. var _this = _super.call(this) || this;
  38181. _this.PBR = true;
  38182. _this.MAINUV1 = false;
  38183. _this.MAINUV2 = false;
  38184. _this.UV1 = false;
  38185. _this.UV2 = false;
  38186. _this.ALBEDO = false;
  38187. _this.ALBEDODIRECTUV = 0;
  38188. _this.VERTEXCOLOR = false;
  38189. _this.AMBIENT = false;
  38190. _this.AMBIENTDIRECTUV = 0;
  38191. _this.AMBIENTINGRAYSCALE = false;
  38192. _this.OPACITY = false;
  38193. _this.VERTEXALPHA = false;
  38194. _this.OPACITYDIRECTUV = 0;
  38195. _this.OPACITYRGB = false;
  38196. _this.ALPHATEST = false;
  38197. _this.DEPTHPREPASS = false;
  38198. _this.ALPHABLEND = false;
  38199. _this.ALPHAFROMALBEDO = false;
  38200. _this.ALPHATESTVALUE = 0.5;
  38201. _this.SPECULAROVERALPHA = false;
  38202. _this.RADIANCEOVERALPHA = false;
  38203. _this.ALPHAFRESNEL = false;
  38204. _this.LINEARALPHAFRESNEL = false;
  38205. _this.PREMULTIPLYALPHA = false;
  38206. _this.EMISSIVE = false;
  38207. _this.EMISSIVEDIRECTUV = 0;
  38208. _this.REFLECTIVITY = false;
  38209. _this.REFLECTIVITYDIRECTUV = 0;
  38210. _this.SPECULARTERM = false;
  38211. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38212. _this.MICROSURFACEAUTOMATIC = false;
  38213. _this.LODBASEDMICROSFURACE = false;
  38214. _this.MICROSURFACEMAP = false;
  38215. _this.MICROSURFACEMAPDIRECTUV = 0;
  38216. _this.METALLICWORKFLOW = false;
  38217. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38218. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38219. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38220. _this.AOSTOREINMETALMAPRED = false;
  38221. _this.ENVIRONMENTBRDF = false;
  38222. _this.NORMAL = false;
  38223. _this.TANGENT = false;
  38224. _this.BUMP = false;
  38225. _this.BUMPDIRECTUV = 0;
  38226. _this.PARALLAX = false;
  38227. _this.PARALLAXOCCLUSION = false;
  38228. _this.NORMALXYSCALE = true;
  38229. _this.LIGHTMAP = false;
  38230. _this.LIGHTMAPDIRECTUV = 0;
  38231. _this.USELIGHTMAPASSHADOWMAP = false;
  38232. _this.REFLECTION = false;
  38233. _this.REFLECTIONMAP_3D = false;
  38234. _this.REFLECTIONMAP_SPHERICAL = false;
  38235. _this.REFLECTIONMAP_PLANAR = false;
  38236. _this.REFLECTIONMAP_CUBIC = false;
  38237. _this.REFLECTIONMAP_PROJECTION = false;
  38238. _this.REFLECTIONMAP_SKYBOX = false;
  38239. _this.REFLECTIONMAP_EXPLICIT = false;
  38240. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38241. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38242. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38243. _this.INVERTCUBICMAP = false;
  38244. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38245. _this.USESPHERICALINVERTEX = false;
  38246. _this.REFLECTIONMAP_OPPOSITEZ = false;
  38247. _this.LODINREFLECTIONALPHA = false;
  38248. _this.GAMMAREFLECTION = false;
  38249. _this.RADIANCEOCCLUSION = false;
  38250. _this.HORIZONOCCLUSION = false;
  38251. _this.REFRACTION = false;
  38252. _this.REFRACTIONMAP_3D = false;
  38253. _this.REFRACTIONMAP_OPPOSITEZ = false;
  38254. _this.LODINREFRACTIONALPHA = false;
  38255. _this.GAMMAREFRACTION = false;
  38256. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38257. _this.INSTANCES = false;
  38258. _this.NUM_BONE_INFLUENCERS = 0;
  38259. _this.BonesPerMesh = 0;
  38260. _this.NONUNIFORMSCALING = false;
  38261. _this.MORPHTARGETS = false;
  38262. _this.MORPHTARGETS_NORMAL = false;
  38263. _this.MORPHTARGETS_TANGENT = false;
  38264. _this.NUM_MORPH_INFLUENCERS = 0;
  38265. _this.IMAGEPROCESSING = false;
  38266. _this.VIGNETTE = false;
  38267. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38268. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38269. _this.TONEMAPPING = false;
  38270. _this.CONTRAST = false;
  38271. _this.COLORCURVES = false;
  38272. _this.COLORGRADING = false;
  38273. _this.COLORGRADING3D = false;
  38274. _this.SAMPLER3DGREENDEPTH = false;
  38275. _this.SAMPLER3DBGRMAP = false;
  38276. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38277. _this.EXPOSURE = false;
  38278. _this.USEPHYSICALLIGHTFALLOFF = false;
  38279. _this.TWOSIDEDLIGHTING = false;
  38280. _this.SHADOWFLOAT = false;
  38281. _this.CLIPPLANE = false;
  38282. _this.POINTSIZE = false;
  38283. _this.FOG = false;
  38284. _this.LOGARITHMICDEPTH = false;
  38285. _this.FORCENORMALFORWARD = false;
  38286. _this.rebuild();
  38287. return _this;
  38288. }
  38289. PBRMaterialDefines.prototype.reset = function () {
  38290. _super.prototype.reset.call(this);
  38291. this.ALPHATESTVALUE = 0.5;
  38292. this.PBR = true;
  38293. };
  38294. return PBRMaterialDefines;
  38295. }(BABYLON.MaterialDefines));
  38296. /**
  38297. * The Physically based material base class of BJS.
  38298. *
  38299. * This offers the main features of a standard PBR material.
  38300. * For more information, please refer to the documentation :
  38301. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38302. */
  38303. var PBRBaseMaterial = /** @class */ (function (_super) {
  38304. __extends(PBRBaseMaterial, _super);
  38305. /**
  38306. * Instantiates a new PBRMaterial instance.
  38307. *
  38308. * @param name The material name
  38309. * @param scene The scene the material will be use in.
  38310. */
  38311. function PBRBaseMaterial(name, scene) {
  38312. var _this = _super.call(this, name, scene) || this;
  38313. /**
  38314. * Intensity of the direct lights e.g. the four lights available in your scene.
  38315. * This impacts both the direct diffuse and specular highlights.
  38316. */
  38317. _this._directIntensity = 1.0;
  38318. /**
  38319. * Intensity of the emissive part of the material.
  38320. * This helps controlling the emissive effect without modifying the emissive color.
  38321. */
  38322. _this._emissiveIntensity = 1.0;
  38323. /**
  38324. * Intensity of the environment e.g. how much the environment will light the object
  38325. * either through harmonics for rough material or through the refelction for shiny ones.
  38326. */
  38327. _this._environmentIntensity = 1.0;
  38328. /**
  38329. * This is a special control allowing the reduction of the specular highlights coming from the
  38330. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38331. */
  38332. _this._specularIntensity = 1.0;
  38333. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38334. /**
  38335. * Debug Control allowing disabling the bump map on this material.
  38336. */
  38337. _this._disableBumpMap = false;
  38338. /**
  38339. * AKA Occlusion Texture Intensity in other nomenclature.
  38340. */
  38341. _this._ambientTextureStrength = 1.0;
  38342. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38343. /**
  38344. * AKA Diffuse Color in other nomenclature.
  38345. */
  38346. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38347. /**
  38348. * AKA Specular Color in other nomenclature.
  38349. */
  38350. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38351. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38352. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38353. /**
  38354. * AKA Glossiness in other nomenclature.
  38355. */
  38356. _this._microSurface = 0.9;
  38357. /**
  38358. * source material index of refraction (IOR)' / 'destination material IOR.
  38359. */
  38360. _this._indexOfRefraction = 0.66;
  38361. /**
  38362. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38363. */
  38364. _this._invertRefractionY = false;
  38365. /**
  38366. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38367. * Materials half opaque for instance using refraction could benefit from this control.
  38368. */
  38369. _this._linkRefractionWithTransparency = false;
  38370. _this._useLightmapAsShadowmap = false;
  38371. /**
  38372. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38373. * makes the reflect vector face the model (under horizon).
  38374. */
  38375. _this._useHorizonOcclusion = true;
  38376. /**
  38377. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38378. * too much the area relying on ambient texture to define their ambient occlusion.
  38379. */
  38380. _this._useRadianceOcclusion = true;
  38381. /**
  38382. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38383. */
  38384. _this._useAlphaFromAlbedoTexture = false;
  38385. /**
  38386. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38387. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38388. */
  38389. _this._useSpecularOverAlpha = true;
  38390. /**
  38391. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38392. */
  38393. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38394. /**
  38395. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38396. */
  38397. _this._useRoughnessFromMetallicTextureAlpha = true;
  38398. /**
  38399. * Specifies if the metallic texture contains the roughness information in its green channel.
  38400. */
  38401. _this._useRoughnessFromMetallicTextureGreen = false;
  38402. /**
  38403. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38404. */
  38405. _this._useMetallnessFromMetallicTextureBlue = false;
  38406. /**
  38407. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38408. */
  38409. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38410. /**
  38411. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38412. */
  38413. _this._useAmbientInGrayScale = false;
  38414. /**
  38415. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38416. * The material will try to infer what glossiness each pixel should be.
  38417. */
  38418. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38419. /**
  38420. * BJS is using an harcoded light falloff based on a manually sets up range.
  38421. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38422. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38423. */
  38424. _this._usePhysicalLightFalloff = true;
  38425. /**
  38426. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38427. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38428. */
  38429. _this._useRadianceOverAlpha = true;
  38430. /**
  38431. * Allows using the bump map in parallax mode.
  38432. */
  38433. _this._useParallax = false;
  38434. /**
  38435. * Allows using the bump map in parallax occlusion mode.
  38436. */
  38437. _this._useParallaxOcclusion = false;
  38438. /**
  38439. * Controls the scale bias of the parallax mode.
  38440. */
  38441. _this._parallaxScaleBias = 0.05;
  38442. /**
  38443. * If sets to true, disables all the lights affecting the material.
  38444. */
  38445. _this._disableLighting = false;
  38446. /**
  38447. * Number of Simultaneous lights allowed on the material.
  38448. */
  38449. _this._maxSimultaneousLights = 4;
  38450. /**
  38451. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38452. */
  38453. _this._invertNormalMapX = false;
  38454. /**
  38455. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38456. */
  38457. _this._invertNormalMapY = false;
  38458. /**
  38459. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38460. */
  38461. _this._twoSidedLighting = false;
  38462. /**
  38463. * Defines the alpha limits in alpha test mode.
  38464. */
  38465. _this._alphaCutOff = 0.4;
  38466. /**
  38467. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38468. */
  38469. _this._forceAlphaTest = false;
  38470. /**
  38471. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38472. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38473. */
  38474. _this._useAlphaFresnel = false;
  38475. /**
  38476. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38477. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38478. */
  38479. _this._useLinearAlphaFresnel = false;
  38480. /**
  38481. * The transparency mode of the material.
  38482. */
  38483. _this._transparencyMode = null;
  38484. /**
  38485. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38486. * from cos thetav and roughness:
  38487. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38488. */
  38489. _this._environmentBRDFTexture = null;
  38490. /**
  38491. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38492. */
  38493. _this._forceIrradianceInFragment = false;
  38494. /**
  38495. * Force normal to face away from face.
  38496. */
  38497. _this._forceNormalForward = false;
  38498. /**
  38499. * Force metallic workflow.
  38500. */
  38501. _this._forceMetallicWorkflow = false;
  38502. _this._renderTargets = new BABYLON.SmartArray(16);
  38503. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38504. // Setup the default processing configuration to the scene.
  38505. _this._attachImageProcessingConfiguration(null);
  38506. _this.getRenderTargetTextures = function () {
  38507. _this._renderTargets.reset();
  38508. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38509. _this._renderTargets.push(_this._reflectionTexture);
  38510. }
  38511. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38512. _this._renderTargets.push(_this._refractionTexture);
  38513. }
  38514. return _this._renderTargets;
  38515. };
  38516. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38517. return _this;
  38518. }
  38519. /**
  38520. * Attaches a new image processing configuration to the PBR Material.
  38521. * @param configuration
  38522. */
  38523. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38524. var _this = this;
  38525. if (configuration === this._imageProcessingConfiguration) {
  38526. return;
  38527. }
  38528. // Detaches observer.
  38529. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38530. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38531. }
  38532. // Pick the scene configuration if needed.
  38533. if (!configuration) {
  38534. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38535. }
  38536. else {
  38537. this._imageProcessingConfiguration = configuration;
  38538. }
  38539. // Attaches observer.
  38540. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38541. _this._markAllSubMeshesAsImageProcessingDirty();
  38542. });
  38543. };
  38544. PBRBaseMaterial.prototype.getClassName = function () {
  38545. return "PBRBaseMaterial";
  38546. };
  38547. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38548. get: function () {
  38549. return this._useLogarithmicDepth;
  38550. },
  38551. set: function (value) {
  38552. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38553. },
  38554. enumerable: true,
  38555. configurable: true
  38556. });
  38557. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38558. /**
  38559. * Gets the current transparency mode.
  38560. */
  38561. get: function () {
  38562. return this._transparencyMode;
  38563. },
  38564. /**
  38565. * Sets the transparency mode of the material.
  38566. */
  38567. set: function (value) {
  38568. if (this._transparencyMode === value) {
  38569. return;
  38570. }
  38571. this._transparencyMode = value;
  38572. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38573. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38574. },
  38575. enumerable: true,
  38576. configurable: true
  38577. });
  38578. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38579. /**
  38580. * Returns true if alpha blending should be disabled.
  38581. */
  38582. get: function () {
  38583. return (this._linkRefractionWithTransparency ||
  38584. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38585. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38586. },
  38587. enumerable: true,
  38588. configurable: true
  38589. });
  38590. /**
  38591. * Specifies whether or not this material should be rendered in alpha blend mode.
  38592. */
  38593. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38594. if (this._disableAlphaBlending) {
  38595. return false;
  38596. }
  38597. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38598. };
  38599. /**
  38600. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38601. */
  38602. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38603. if (this._disableAlphaBlending) {
  38604. return false;
  38605. }
  38606. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38607. };
  38608. /**
  38609. * Specifies whether or not this material should be rendered in alpha test mode.
  38610. */
  38611. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38612. if (this._forceAlphaTest) {
  38613. return true;
  38614. }
  38615. if (this._linkRefractionWithTransparency) {
  38616. return false;
  38617. }
  38618. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38619. };
  38620. /**
  38621. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38622. */
  38623. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38624. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38625. };
  38626. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38627. return this._albedoTexture;
  38628. };
  38629. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38630. var _this = this;
  38631. if (subMesh.effect && this.isFrozen) {
  38632. if (this._wasPreviouslyReady) {
  38633. return true;
  38634. }
  38635. }
  38636. if (!subMesh._materialDefines) {
  38637. subMesh._materialDefines = new PBRMaterialDefines();
  38638. }
  38639. var scene = this.getScene();
  38640. var defines = subMesh._materialDefines;
  38641. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38642. if (defines._renderId === scene.getRenderId()) {
  38643. return true;
  38644. }
  38645. }
  38646. var engine = scene.getEngine();
  38647. // Lights
  38648. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38649. defines._needNormals = true;
  38650. // Textures
  38651. if (defines._areTexturesDirty) {
  38652. defines._needUVs = false;
  38653. if (scene.texturesEnabled) {
  38654. if (scene.getEngine().getCaps().textureLOD) {
  38655. defines.LODBASEDMICROSFURACE = true;
  38656. }
  38657. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38658. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38659. return false;
  38660. }
  38661. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38662. }
  38663. else {
  38664. defines.ALBEDO = false;
  38665. }
  38666. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38667. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38668. return false;
  38669. }
  38670. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38671. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38672. }
  38673. else {
  38674. defines.AMBIENT = false;
  38675. }
  38676. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38677. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38678. return false;
  38679. }
  38680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38681. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38682. }
  38683. else {
  38684. defines.OPACITY = false;
  38685. }
  38686. var reflectionTexture = this._getReflectionTexture();
  38687. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38688. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38689. return false;
  38690. }
  38691. defines.REFLECTION = true;
  38692. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38693. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38694. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38695. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38696. defines.INVERTCUBICMAP = true;
  38697. }
  38698. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38699. switch (reflectionTexture.coordinatesMode) {
  38700. case BABYLON.Texture.CUBIC_MODE:
  38701. case BABYLON.Texture.INVCUBIC_MODE:
  38702. defines.REFLECTIONMAP_CUBIC = true;
  38703. break;
  38704. case BABYLON.Texture.EXPLICIT_MODE:
  38705. defines.REFLECTIONMAP_EXPLICIT = true;
  38706. break;
  38707. case BABYLON.Texture.PLANAR_MODE:
  38708. defines.REFLECTIONMAP_PLANAR = true;
  38709. break;
  38710. case BABYLON.Texture.PROJECTION_MODE:
  38711. defines.REFLECTIONMAP_PROJECTION = true;
  38712. break;
  38713. case BABYLON.Texture.SKYBOX_MODE:
  38714. defines.REFLECTIONMAP_SKYBOX = true;
  38715. break;
  38716. case BABYLON.Texture.SPHERICAL_MODE:
  38717. defines.REFLECTIONMAP_SPHERICAL = true;
  38718. break;
  38719. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38720. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38721. break;
  38722. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38723. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38724. break;
  38725. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38726. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38727. break;
  38728. }
  38729. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38730. if (reflectionTexture.sphericalPolynomial) {
  38731. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38732. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38733. defines.USESPHERICALINVERTEX = false;
  38734. }
  38735. else {
  38736. defines.USESPHERICALINVERTEX = true;
  38737. }
  38738. }
  38739. }
  38740. }
  38741. else {
  38742. defines.REFLECTION = false;
  38743. defines.REFLECTIONMAP_3D = false;
  38744. defines.REFLECTIONMAP_SPHERICAL = false;
  38745. defines.REFLECTIONMAP_PLANAR = false;
  38746. defines.REFLECTIONMAP_CUBIC = false;
  38747. defines.REFLECTIONMAP_PROJECTION = false;
  38748. defines.REFLECTIONMAP_SKYBOX = false;
  38749. defines.REFLECTIONMAP_EXPLICIT = false;
  38750. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38751. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38752. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38753. defines.INVERTCUBICMAP = false;
  38754. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38755. defines.USESPHERICALINVERTEX = false;
  38756. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38757. defines.LODINREFLECTIONALPHA = false;
  38758. defines.GAMMAREFLECTION = false;
  38759. }
  38760. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38761. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38762. return false;
  38763. }
  38764. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38765. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38766. }
  38767. else {
  38768. defines.LIGHTMAP = false;
  38769. }
  38770. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38771. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38772. return false;
  38773. }
  38774. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38775. }
  38776. else {
  38777. defines.EMISSIVE = false;
  38778. }
  38779. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38780. if (this._metallicTexture) {
  38781. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38782. return false;
  38783. }
  38784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38785. defines.METALLICWORKFLOW = true;
  38786. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38787. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38788. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38789. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38790. }
  38791. else if (this._reflectivityTexture) {
  38792. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38793. return false;
  38794. }
  38795. defines.METALLICWORKFLOW = false;
  38796. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38797. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38798. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38799. }
  38800. else {
  38801. defines.METALLICWORKFLOW = false;
  38802. defines.REFLECTIVITY = false;
  38803. }
  38804. if (this._microSurfaceTexture) {
  38805. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38806. return false;
  38807. }
  38808. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38809. }
  38810. else {
  38811. defines.MICROSURFACEMAP = false;
  38812. }
  38813. }
  38814. else {
  38815. defines.REFLECTIVITY = false;
  38816. defines.MICROSURFACEMAP = false;
  38817. }
  38818. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38819. // Bump texure can not be none blocking.
  38820. if (!this._bumpTexture.isReady()) {
  38821. return false;
  38822. }
  38823. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38824. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38825. defines.PARALLAX = true;
  38826. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38827. }
  38828. else {
  38829. defines.PARALLAX = false;
  38830. }
  38831. }
  38832. else {
  38833. defines.BUMP = false;
  38834. }
  38835. var refractionTexture = this._getRefractionTexture();
  38836. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38837. if (!refractionTexture.isReadyOrNotBlocking()) {
  38838. return false;
  38839. }
  38840. defines.REFRACTION = true;
  38841. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38842. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38843. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38844. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38845. if (this._linkRefractionWithTransparency) {
  38846. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38847. }
  38848. }
  38849. else {
  38850. defines.REFRACTION = false;
  38851. }
  38852. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38853. // This is blocking.
  38854. if (!this._environmentBRDFTexture.isReady()) {
  38855. return false;
  38856. }
  38857. defines.ENVIRONMENTBRDF = true;
  38858. }
  38859. else {
  38860. defines.ENVIRONMENTBRDF = false;
  38861. }
  38862. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38863. defines.ALPHAFROMALBEDO = true;
  38864. }
  38865. else {
  38866. defines.ALPHAFROMALBEDO = false;
  38867. }
  38868. }
  38869. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38870. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38871. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38872. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38873. defines.METALLICWORKFLOW = true;
  38874. }
  38875. else {
  38876. defines.METALLICWORKFLOW = false;
  38877. }
  38878. if (!this.backFaceCulling && this._twoSidedLighting) {
  38879. defines.TWOSIDEDLIGHTING = true;
  38880. }
  38881. else {
  38882. defines.TWOSIDEDLIGHTING = false;
  38883. }
  38884. defines.ALPHATESTVALUE = this._alphaCutOff;
  38885. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38886. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38887. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38888. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38889. }
  38890. if (defines._areImageProcessingDirty) {
  38891. if (!this._imageProcessingConfiguration.isReady()) {
  38892. return false;
  38893. }
  38894. this._imageProcessingConfiguration.prepareDefines(defines);
  38895. }
  38896. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38897. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38898. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38899. // Misc.
  38900. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  38901. // Values that need to be evaluated on every frame
  38902. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  38903. // Attribs
  38904. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38905. var bufferMesh = null;
  38906. if (mesh instanceof BABYLON.InstancedMesh) {
  38907. bufferMesh = mesh.sourceMesh;
  38908. }
  38909. else if (mesh instanceof BABYLON.Mesh) {
  38910. bufferMesh = mesh;
  38911. }
  38912. if (bufferMesh) {
  38913. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38914. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38915. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38916. var normals = normalVertexBuffer.getData();
  38917. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38918. var strideSize = normalVertexBuffer.getStrideSize();
  38919. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38920. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38921. defines.NORMAL = false;
  38922. }
  38923. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38924. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38925. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38926. var tangents = tangentVertexBuffer.getData();
  38927. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38928. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38929. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38930. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38931. defines.TANGENT = false;
  38932. }
  38933. }
  38934. }
  38935. else {
  38936. if (!scene.getEngine().getCaps().standardDerivatives) {
  38937. bufferMesh.createNormals(true);
  38938. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38939. }
  38940. }
  38941. }
  38942. }
  38943. // Get correct effect
  38944. if (defines.isDirty) {
  38945. defines.markAsProcessed();
  38946. scene.resetCachedMaterial();
  38947. // Fallbacks
  38948. var fallbacks = new BABYLON.EffectFallbacks();
  38949. var fallbackRank = 0;
  38950. if (defines.USESPHERICALINVERTEX) {
  38951. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38952. }
  38953. if (defines.FOG) {
  38954. fallbacks.addFallback(fallbackRank, "FOG");
  38955. }
  38956. if (defines.POINTSIZE) {
  38957. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38958. }
  38959. if (defines.LOGARITHMICDEPTH) {
  38960. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38961. }
  38962. if (defines.PARALLAX) {
  38963. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38964. }
  38965. if (defines.PARALLAXOCCLUSION) {
  38966. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38967. }
  38968. if (defines.ENVIRONMENTBRDF) {
  38969. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38970. }
  38971. if (defines.TANGENT) {
  38972. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38973. }
  38974. if (defines.BUMP) {
  38975. fallbacks.addFallback(fallbackRank++, "BUMP");
  38976. }
  38977. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38978. if (defines.SPECULARTERM) {
  38979. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38980. }
  38981. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38982. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38983. }
  38984. if (defines.LIGHTMAP) {
  38985. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38986. }
  38987. if (defines.NORMAL) {
  38988. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38989. }
  38990. if (defines.AMBIENT) {
  38991. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38992. }
  38993. if (defines.EMISSIVE) {
  38994. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38995. }
  38996. if (defines.VERTEXCOLOR) {
  38997. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38998. }
  38999. if (defines.NUM_BONE_INFLUENCERS > 0) {
  39000. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  39001. }
  39002. if (defines.MORPHTARGETS) {
  39003. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  39004. }
  39005. //Attributes
  39006. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39007. if (defines.NORMAL) {
  39008. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39009. }
  39010. if (defines.TANGENT) {
  39011. attribs.push(BABYLON.VertexBuffer.TangentKind);
  39012. }
  39013. if (defines.UV1) {
  39014. attribs.push(BABYLON.VertexBuffer.UVKind);
  39015. }
  39016. if (defines.UV2) {
  39017. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39018. }
  39019. if (defines.VERTEXCOLOR) {
  39020. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39021. }
  39022. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39023. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39024. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39025. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39026. "vFogInfos", "vFogColor", "pointSize",
  39027. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39028. "mBones",
  39029. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39030. "vLightingIntensity",
  39031. "logarithmicDepthConstant",
  39032. "vSphericalX", "vSphericalY", "vSphericalZ",
  39033. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39034. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39035. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  39036. "vTangentSpaceParams"
  39037. ];
  39038. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  39039. "bumpSampler", "lightmapSampler", "opacitySampler",
  39040. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  39041. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  39042. "microSurfaceSampler", "environmentBrdfSampler"];
  39043. var uniformBuffers = ["Material", "Scene"];
  39044. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39045. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39046. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39047. uniformsNames: uniforms,
  39048. uniformBuffersNames: uniformBuffers,
  39049. samplers: samplers,
  39050. defines: defines,
  39051. maxSimultaneousLights: this._maxSimultaneousLights
  39052. });
  39053. var onCompiled = function (effect) {
  39054. if (_this.onCompiled) {
  39055. _this.onCompiled(effect);
  39056. }
  39057. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39058. };
  39059. var join = defines.toString();
  39060. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39061. attributes: attribs,
  39062. uniformsNames: uniforms,
  39063. uniformBuffersNames: uniformBuffers,
  39064. samplers: samplers,
  39065. defines: join,
  39066. fallbacks: fallbacks,
  39067. onCompiled: onCompiled,
  39068. onError: this.onError,
  39069. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39070. }, engine), defines);
  39071. this.buildUniformLayout();
  39072. }
  39073. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39074. return false;
  39075. }
  39076. defines._renderId = scene.getRenderId();
  39077. this._wasPreviouslyReady = true;
  39078. return true;
  39079. };
  39080. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39081. // Order is important !
  39082. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39083. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39084. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39085. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39086. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39087. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39088. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39089. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39090. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39091. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39092. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39093. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39094. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39095. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39096. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39097. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39098. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39099. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39100. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39101. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39102. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39103. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39104. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39105. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39106. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  39107. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  39108. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39109. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39110. this._uniformBuffer.addUniform("pointSize", 1);
  39111. this._uniformBuffer.create();
  39112. };
  39113. PBRBaseMaterial.prototype.unbind = function () {
  39114. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39115. this._uniformBuffer.setTexture("reflectionSampler", null);
  39116. }
  39117. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39118. this._uniformBuffer.setTexture("refractionSampler", null);
  39119. }
  39120. _super.prototype.unbind.call(this);
  39121. };
  39122. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39123. this._activeEffect.setMatrix("world", world);
  39124. };
  39125. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39126. var scene = this.getScene();
  39127. var defines = subMesh._materialDefines;
  39128. if (!defines) {
  39129. return;
  39130. }
  39131. var effect = subMesh.effect;
  39132. if (!effect) {
  39133. return;
  39134. }
  39135. this._activeEffect = effect;
  39136. // Matrices
  39137. this.bindOnlyWorldMatrix(world);
  39138. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39139. // Bones
  39140. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39141. var reflectionTexture = null;
  39142. if (mustRebind) {
  39143. this._uniformBuffer.bindToEffect(effect, "Material");
  39144. this.bindViewProjection(effect);
  39145. reflectionTexture = this._getReflectionTexture();
  39146. var refractionTexture = this._getRefractionTexture();
  39147. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39148. // Texture uniforms
  39149. if (scene.texturesEnabled) {
  39150. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39151. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39152. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  39153. }
  39154. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39155. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39156. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39157. }
  39158. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39159. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39160. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39161. }
  39162. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39163. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39164. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39165. var polynomials = reflectionTexture.sphericalPolynomial;
  39166. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  39167. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  39168. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  39169. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  39170. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  39171. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  39172. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  39173. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  39174. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  39175. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  39176. }
  39177. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  39178. }
  39179. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39180. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39181. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39182. }
  39183. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39184. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39185. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39186. }
  39187. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39188. if (this._metallicTexture) {
  39189. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39190. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  39191. }
  39192. else if (this._reflectivityTexture) {
  39193. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39194. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  39195. }
  39196. if (this._microSurfaceTexture) {
  39197. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39198. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  39199. }
  39200. }
  39201. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39202. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39203. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39204. if (scene._mirroredCameraPosition) {
  39205. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39206. }
  39207. else {
  39208. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39209. }
  39210. }
  39211. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39212. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  39213. var depth = 1.0;
  39214. if (!refractionTexture.isCube) {
  39215. if (refractionTexture.depth) {
  39216. depth = refractionTexture.depth;
  39217. }
  39218. }
  39219. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39220. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  39221. }
  39222. }
  39223. // Point size
  39224. if (this.pointsCloud) {
  39225. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39226. }
  39227. // Colors
  39228. if (defines.METALLICWORKFLOW) {
  39229. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39230. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39231. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39232. }
  39233. else {
  39234. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  39235. }
  39236. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  39237. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  39238. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  39239. // Misc
  39240. this._lightingInfos.x = this._directIntensity;
  39241. this._lightingInfos.y = this._emissiveIntensity;
  39242. this._lightingInfos.z = this._environmentIntensity;
  39243. this._lightingInfos.w = this._specularIntensity;
  39244. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39245. }
  39246. // Textures
  39247. if (scene.texturesEnabled) {
  39248. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39249. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39250. }
  39251. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39252. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39253. }
  39254. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39255. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39256. }
  39257. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39258. if (defines.LODBASEDMICROSFURACE) {
  39259. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  39260. }
  39261. else {
  39262. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  39263. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  39264. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  39265. }
  39266. }
  39267. if (defines.ENVIRONMENTBRDF) {
  39268. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  39269. }
  39270. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39271. if (defines.LODBASEDMICROSFURACE) {
  39272. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39273. }
  39274. else {
  39275. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39276. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39277. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39278. }
  39279. }
  39280. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39281. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39282. }
  39283. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39284. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39285. }
  39286. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39287. if (this._metallicTexture) {
  39288. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39289. }
  39290. else if (this._reflectivityTexture) {
  39291. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39292. }
  39293. if (this._microSurfaceTexture) {
  39294. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39295. }
  39296. }
  39297. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39298. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39299. }
  39300. }
  39301. // Clip plane
  39302. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39303. // Colors
  39304. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39305. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39306. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39307. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39308. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39309. }
  39310. if (mustRebind || !this.isFrozen) {
  39311. // Lights
  39312. if (scene.lightsEnabled && !this._disableLighting) {
  39313. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39314. }
  39315. // View
  39316. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39317. this.bindView(effect);
  39318. }
  39319. // Fog
  39320. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39321. // Morph targets
  39322. if (defines.NUM_MORPH_INFLUENCERS) {
  39323. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39324. }
  39325. // image processing
  39326. this._imageProcessingConfiguration.bind(this._activeEffect);
  39327. // Log. depth
  39328. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39329. }
  39330. this._uniformBuffer.update();
  39331. this._afterBind(mesh);
  39332. };
  39333. PBRBaseMaterial.prototype.getAnimatables = function () {
  39334. var results = [];
  39335. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39336. results.push(this._albedoTexture);
  39337. }
  39338. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39339. results.push(this._ambientTexture);
  39340. }
  39341. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39342. results.push(this._opacityTexture);
  39343. }
  39344. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39345. results.push(this._reflectionTexture);
  39346. }
  39347. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39348. results.push(this._emissiveTexture);
  39349. }
  39350. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39351. results.push(this._metallicTexture);
  39352. }
  39353. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39354. results.push(this._reflectivityTexture);
  39355. }
  39356. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39357. results.push(this._bumpTexture);
  39358. }
  39359. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39360. results.push(this._lightmapTexture);
  39361. }
  39362. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39363. results.push(this._refractionTexture);
  39364. }
  39365. return results;
  39366. };
  39367. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39368. if (this._reflectionTexture) {
  39369. return this._reflectionTexture;
  39370. }
  39371. return this.getScene().environmentTexture;
  39372. };
  39373. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39374. if (this._refractionTexture) {
  39375. return this._refractionTexture;
  39376. }
  39377. if (this._linkRefractionWithTransparency) {
  39378. return this.getScene().environmentTexture;
  39379. }
  39380. return null;
  39381. };
  39382. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39383. if (forceDisposeTextures) {
  39384. if (this._albedoTexture) {
  39385. this._albedoTexture.dispose();
  39386. }
  39387. if (this._ambientTexture) {
  39388. this._ambientTexture.dispose();
  39389. }
  39390. if (this._opacityTexture) {
  39391. this._opacityTexture.dispose();
  39392. }
  39393. if (this._reflectionTexture) {
  39394. this._reflectionTexture.dispose();
  39395. }
  39396. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39397. this._environmentBRDFTexture.dispose();
  39398. }
  39399. if (this._emissiveTexture) {
  39400. this._emissiveTexture.dispose();
  39401. }
  39402. if (this._metallicTexture) {
  39403. this._metallicTexture.dispose();
  39404. }
  39405. if (this._reflectivityTexture) {
  39406. this._reflectivityTexture.dispose();
  39407. }
  39408. if (this._bumpTexture) {
  39409. this._bumpTexture.dispose();
  39410. }
  39411. if (this._lightmapTexture) {
  39412. this._lightmapTexture.dispose();
  39413. }
  39414. if (this._refractionTexture) {
  39415. this._refractionTexture.dispose();
  39416. }
  39417. }
  39418. this._renderTargets.dispose();
  39419. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39420. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39421. }
  39422. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39423. };
  39424. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39425. __decorate([
  39426. BABYLON.serializeAsImageProcessingConfiguration()
  39427. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39428. __decorate([
  39429. BABYLON.serialize()
  39430. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39431. __decorate([
  39432. BABYLON.serialize()
  39433. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39434. return PBRBaseMaterial;
  39435. }(BABYLON.PushMaterial));
  39436. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39437. })(BABYLON || (BABYLON = {}));
  39438. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39439. var BABYLON;
  39440. (function (BABYLON) {
  39441. /**
  39442. * The Physically based simple base material of BJS.
  39443. *
  39444. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39445. * It is used as the base class for both the specGloss and metalRough conventions.
  39446. */
  39447. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39448. __extends(PBRBaseSimpleMaterial, _super);
  39449. /**
  39450. * Instantiates a new PBRMaterial instance.
  39451. *
  39452. * @param name The material name
  39453. * @param scene The scene the material will be use in.
  39454. */
  39455. function PBRBaseSimpleMaterial(name, scene) {
  39456. var _this = _super.call(this, name, scene) || this;
  39457. /**
  39458. * Number of Simultaneous lights allowed on the material.
  39459. */
  39460. _this.maxSimultaneousLights = 4;
  39461. /**
  39462. * If sets to true, disables all the lights affecting the material.
  39463. */
  39464. _this.disableLighting = false;
  39465. /**
  39466. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39467. */
  39468. _this.invertNormalMapX = false;
  39469. /**
  39470. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39471. */
  39472. _this.invertNormalMapY = false;
  39473. /**
  39474. * Emissivie color used to self-illuminate the model.
  39475. */
  39476. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39477. /**
  39478. * Occlusion Channel Strenght.
  39479. */
  39480. _this.occlusionStrength = 1.0;
  39481. _this.useLightmapAsShadowmap = false;
  39482. _this._useAlphaFromAlbedoTexture = true;
  39483. _this._useAmbientInGrayScale = true;
  39484. return _this;
  39485. }
  39486. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39487. /**
  39488. * Gets the current double sided mode.
  39489. */
  39490. get: function () {
  39491. return this._twoSidedLighting;
  39492. },
  39493. /**
  39494. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39495. */
  39496. set: function (value) {
  39497. if (this._twoSidedLighting === value) {
  39498. return;
  39499. }
  39500. this._twoSidedLighting = value;
  39501. this.backFaceCulling = !value;
  39502. this._markAllSubMeshesAsTexturesDirty();
  39503. },
  39504. enumerable: true,
  39505. configurable: true
  39506. });
  39507. /**
  39508. * Return the active textures of the material.
  39509. */
  39510. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39511. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39512. if (this.environmentTexture) {
  39513. activeTextures.push(this.environmentTexture);
  39514. }
  39515. if (this.normalTexture) {
  39516. activeTextures.push(this.normalTexture);
  39517. }
  39518. if (this.emissiveTexture) {
  39519. activeTextures.push(this.emissiveTexture);
  39520. }
  39521. if (this.occlusionTexture) {
  39522. activeTextures.push(this.occlusionTexture);
  39523. }
  39524. if (this.lightmapTexture) {
  39525. activeTextures.push(this.lightmapTexture);
  39526. }
  39527. return activeTextures;
  39528. };
  39529. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39530. if (_super.prototype.hasTexture.call(this, texture)) {
  39531. return true;
  39532. }
  39533. if (this.lightmapTexture === texture) {
  39534. return true;
  39535. }
  39536. return false;
  39537. };
  39538. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39539. return "PBRBaseSimpleMaterial";
  39540. };
  39541. __decorate([
  39542. BABYLON.serialize(),
  39543. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39544. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39545. __decorate([
  39546. BABYLON.serialize(),
  39547. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39548. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39549. __decorate([
  39550. BABYLON.serializeAsTexture(),
  39551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39552. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39553. __decorate([
  39554. BABYLON.serialize(),
  39555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39556. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39557. __decorate([
  39558. BABYLON.serialize(),
  39559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39560. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39561. __decorate([
  39562. BABYLON.serializeAsTexture(),
  39563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39564. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39565. __decorate([
  39566. BABYLON.serializeAsColor3("emissive"),
  39567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39568. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39569. __decorate([
  39570. BABYLON.serializeAsTexture(),
  39571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39572. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39573. __decorate([
  39574. BABYLON.serialize(),
  39575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39576. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39577. __decorate([
  39578. BABYLON.serializeAsTexture(),
  39579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39580. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39581. __decorate([
  39582. BABYLON.serialize(),
  39583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39584. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39585. __decorate([
  39586. BABYLON.serialize()
  39587. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39588. __decorate([
  39589. BABYLON.serializeAsTexture(),
  39590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39591. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39592. __decorate([
  39593. BABYLON.serialize(),
  39594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39595. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39596. return PBRBaseSimpleMaterial;
  39597. }(BABYLON.PBRBaseMaterial));
  39598. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39599. })(BABYLON || (BABYLON = {}));
  39600. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39601. var BABYLON;
  39602. (function (BABYLON) {
  39603. /**
  39604. * The Physically based material of BJS.
  39605. *
  39606. * This offers the main features of a standard PBR material.
  39607. * For more information, please refer to the documentation :
  39608. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39609. */
  39610. var PBRMaterial = /** @class */ (function (_super) {
  39611. __extends(PBRMaterial, _super);
  39612. /**
  39613. * Instantiates a new PBRMaterial instance.
  39614. *
  39615. * @param name The material name
  39616. * @param scene The scene the material will be use in.
  39617. */
  39618. function PBRMaterial(name, scene) {
  39619. var _this = _super.call(this, name, scene) || this;
  39620. /**
  39621. * Intensity of the direct lights e.g. the four lights available in your scene.
  39622. * This impacts both the direct diffuse and specular highlights.
  39623. */
  39624. _this.directIntensity = 1.0;
  39625. /**
  39626. * Intensity of the emissive part of the material.
  39627. * This helps controlling the emissive effect without modifying the emissive color.
  39628. */
  39629. _this.emissiveIntensity = 1.0;
  39630. /**
  39631. * Intensity of the environment e.g. how much the environment will light the object
  39632. * either through harmonics for rough material or through the refelction for shiny ones.
  39633. */
  39634. _this.environmentIntensity = 1.0;
  39635. /**
  39636. * This is a special control allowing the reduction of the specular highlights coming from the
  39637. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39638. */
  39639. _this.specularIntensity = 1.0;
  39640. /**
  39641. * Debug Control allowing disabling the bump map on this material.
  39642. */
  39643. _this.disableBumpMap = false;
  39644. /**
  39645. * AKA Occlusion Texture Intensity in other nomenclature.
  39646. */
  39647. _this.ambientTextureStrength = 1.0;
  39648. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39649. /**
  39650. * AKA Diffuse Color in other nomenclature.
  39651. */
  39652. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39653. /**
  39654. * AKA Specular Color in other nomenclature.
  39655. */
  39656. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39657. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39658. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39659. /**
  39660. * AKA Glossiness in other nomenclature.
  39661. */
  39662. _this.microSurface = 1.0;
  39663. /**
  39664. * source material index of refraction (IOR)' / 'destination material IOR.
  39665. */
  39666. _this.indexOfRefraction = 0.66;
  39667. /**
  39668. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39669. */
  39670. _this.invertRefractionY = false;
  39671. /**
  39672. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39673. * Materials half opaque for instance using refraction could benefit from this control.
  39674. */
  39675. _this.linkRefractionWithTransparency = false;
  39676. _this.useLightmapAsShadowmap = false;
  39677. /**
  39678. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39679. */
  39680. _this.useAlphaFromAlbedoTexture = false;
  39681. /**
  39682. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39683. */
  39684. _this.forceAlphaTest = false;
  39685. /**
  39686. * Defines the alpha limits in alpha test mode.
  39687. */
  39688. _this.alphaCutOff = 0.4;
  39689. /**
  39690. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39691. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39692. */
  39693. _this.useSpecularOverAlpha = true;
  39694. /**
  39695. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39696. */
  39697. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39698. /**
  39699. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39700. */
  39701. _this.useRoughnessFromMetallicTextureAlpha = true;
  39702. /**
  39703. * Specifies if the metallic texture contains the roughness information in its green channel.
  39704. */
  39705. _this.useRoughnessFromMetallicTextureGreen = false;
  39706. /**
  39707. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39708. */
  39709. _this.useMetallnessFromMetallicTextureBlue = false;
  39710. /**
  39711. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39712. */
  39713. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39714. /**
  39715. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39716. */
  39717. _this.useAmbientInGrayScale = false;
  39718. /**
  39719. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39720. * The material will try to infer what glossiness each pixel should be.
  39721. */
  39722. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39723. /**
  39724. * BJS is using an harcoded light falloff based on a manually sets up range.
  39725. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39726. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39727. */
  39728. _this.usePhysicalLightFalloff = true;
  39729. /**
  39730. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39731. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39732. */
  39733. _this.useRadianceOverAlpha = true;
  39734. /**
  39735. * Allows using the bump map in parallax mode.
  39736. */
  39737. _this.useParallax = false;
  39738. /**
  39739. * Allows using the bump map in parallax occlusion mode.
  39740. */
  39741. _this.useParallaxOcclusion = false;
  39742. /**
  39743. * Controls the scale bias of the parallax mode.
  39744. */
  39745. _this.parallaxScaleBias = 0.05;
  39746. /**
  39747. * If sets to true, disables all the lights affecting the material.
  39748. */
  39749. _this.disableLighting = false;
  39750. /**
  39751. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39752. */
  39753. _this.forceIrradianceInFragment = false;
  39754. /**
  39755. * Number of Simultaneous lights allowed on the material.
  39756. */
  39757. _this.maxSimultaneousLights = 4;
  39758. /**
  39759. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39760. */
  39761. _this.invertNormalMapX = false;
  39762. /**
  39763. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39764. */
  39765. _this.invertNormalMapY = false;
  39766. /**
  39767. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39768. */
  39769. _this.twoSidedLighting = false;
  39770. /**
  39771. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39772. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39773. */
  39774. _this.useAlphaFresnel = false;
  39775. /**
  39776. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39777. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39778. */
  39779. _this.useLinearAlphaFresnel = false;
  39780. /**
  39781. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39782. * And/Or occlude the blended part.
  39783. */
  39784. _this.environmentBRDFTexture = null;
  39785. /**
  39786. * Force normal to face away from face.
  39787. */
  39788. _this.forceNormalForward = false;
  39789. /**
  39790. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39791. * makes the reflect vector face the model (under horizon).
  39792. */
  39793. _this.useHorizonOcclusion = true;
  39794. /**
  39795. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39796. * too much the area relying on ambient texture to define their ambient occlusion.
  39797. */
  39798. _this.useRadianceOcclusion = true;
  39799. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39800. return _this;
  39801. }
  39802. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39803. /**
  39804. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39805. */
  39806. get: function () {
  39807. return this._PBRMATERIAL_OPAQUE;
  39808. },
  39809. enumerable: true,
  39810. configurable: true
  39811. });
  39812. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39813. /**
  39814. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39815. */
  39816. get: function () {
  39817. return this._PBRMATERIAL_ALPHATEST;
  39818. },
  39819. enumerable: true,
  39820. configurable: true
  39821. });
  39822. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39823. /**
  39824. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39825. */
  39826. get: function () {
  39827. return this._PBRMATERIAL_ALPHABLEND;
  39828. },
  39829. enumerable: true,
  39830. configurable: true
  39831. });
  39832. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39833. /**
  39834. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39835. * They are also discarded below the alpha cutoff threshold to improve performances.
  39836. */
  39837. get: function () {
  39838. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39839. },
  39840. enumerable: true,
  39841. configurable: true
  39842. });
  39843. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39844. /**
  39845. * Gets the image processing configuration used either in this material.
  39846. */
  39847. get: function () {
  39848. return this._imageProcessingConfiguration;
  39849. },
  39850. /**
  39851. * Sets the Default image processing configuration used either in the this material.
  39852. *
  39853. * If sets to null, the scene one is in use.
  39854. */
  39855. set: function (value) {
  39856. this._attachImageProcessingConfiguration(value);
  39857. // Ensure the effect will be rebuilt.
  39858. this._markAllSubMeshesAsTexturesDirty();
  39859. },
  39860. enumerable: true,
  39861. configurable: true
  39862. });
  39863. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39864. /**
  39865. * Gets wether the color curves effect is enabled.
  39866. */
  39867. get: function () {
  39868. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39869. },
  39870. /**
  39871. * Sets wether the color curves effect is enabled.
  39872. */
  39873. set: function (value) {
  39874. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39875. },
  39876. enumerable: true,
  39877. configurable: true
  39878. });
  39879. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39880. /**
  39881. * Gets wether the color grading effect is enabled.
  39882. */
  39883. get: function () {
  39884. return this.imageProcessingConfiguration.colorGradingEnabled;
  39885. },
  39886. /**
  39887. * Gets wether the color grading effect is enabled.
  39888. */
  39889. set: function (value) {
  39890. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39891. },
  39892. enumerable: true,
  39893. configurable: true
  39894. });
  39895. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39896. /**
  39897. * Gets wether tonemapping is enabled or not.
  39898. */
  39899. get: function () {
  39900. return this._imageProcessingConfiguration.toneMappingEnabled;
  39901. },
  39902. /**
  39903. * Sets wether tonemapping is enabled or not
  39904. */
  39905. set: function (value) {
  39906. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39907. },
  39908. enumerable: true,
  39909. configurable: true
  39910. });
  39911. ;
  39912. ;
  39913. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39914. /**
  39915. * The camera exposure used on this material.
  39916. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39917. * This corresponds to a photographic exposure.
  39918. */
  39919. get: function () {
  39920. return this._imageProcessingConfiguration.exposure;
  39921. },
  39922. /**
  39923. * The camera exposure used on this material.
  39924. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39925. * This corresponds to a photographic exposure.
  39926. */
  39927. set: function (value) {
  39928. this._imageProcessingConfiguration.exposure = value;
  39929. },
  39930. enumerable: true,
  39931. configurable: true
  39932. });
  39933. ;
  39934. ;
  39935. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39936. /**
  39937. * Gets The camera contrast used on this material.
  39938. */
  39939. get: function () {
  39940. return this._imageProcessingConfiguration.contrast;
  39941. },
  39942. /**
  39943. * Sets The camera contrast used on this material.
  39944. */
  39945. set: function (value) {
  39946. this._imageProcessingConfiguration.contrast = value;
  39947. },
  39948. enumerable: true,
  39949. configurable: true
  39950. });
  39951. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39952. /**
  39953. * Gets the Color Grading 2D Lookup Texture.
  39954. */
  39955. get: function () {
  39956. return this._imageProcessingConfiguration.colorGradingTexture;
  39957. },
  39958. /**
  39959. * Sets the Color Grading 2D Lookup Texture.
  39960. */
  39961. set: function (value) {
  39962. this._imageProcessingConfiguration.colorGradingTexture = value;
  39963. },
  39964. enumerable: true,
  39965. configurable: true
  39966. });
  39967. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39968. /**
  39969. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39970. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39971. * 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;
  39972. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39973. */
  39974. get: function () {
  39975. return this._imageProcessingConfiguration.colorCurves;
  39976. },
  39977. /**
  39978. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39979. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39980. * 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;
  39981. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39982. */
  39983. set: function (value) {
  39984. this._imageProcessingConfiguration.colorCurves = value;
  39985. },
  39986. enumerable: true,
  39987. configurable: true
  39988. });
  39989. PBRMaterial.prototype.getClassName = function () {
  39990. return "PBRMaterial";
  39991. };
  39992. PBRMaterial.prototype.getActiveTextures = function () {
  39993. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39994. if (this._albedoTexture) {
  39995. activeTextures.push(this._albedoTexture);
  39996. }
  39997. if (this._ambientTexture) {
  39998. activeTextures.push(this._ambientTexture);
  39999. }
  40000. if (this._opacityTexture) {
  40001. activeTextures.push(this._opacityTexture);
  40002. }
  40003. if (this._reflectionTexture) {
  40004. activeTextures.push(this._reflectionTexture);
  40005. }
  40006. if (this._emissiveTexture) {
  40007. activeTextures.push(this._emissiveTexture);
  40008. }
  40009. if (this._reflectivityTexture) {
  40010. activeTextures.push(this._reflectivityTexture);
  40011. }
  40012. if (this._metallicTexture) {
  40013. activeTextures.push(this._metallicTexture);
  40014. }
  40015. if (this._microSurfaceTexture) {
  40016. activeTextures.push(this._microSurfaceTexture);
  40017. }
  40018. if (this._bumpTexture) {
  40019. activeTextures.push(this._bumpTexture);
  40020. }
  40021. if (this._lightmapTexture) {
  40022. activeTextures.push(this._lightmapTexture);
  40023. }
  40024. if (this._refractionTexture) {
  40025. activeTextures.push(this._refractionTexture);
  40026. }
  40027. return activeTextures;
  40028. };
  40029. PBRMaterial.prototype.hasTexture = function (texture) {
  40030. if (_super.prototype.hasTexture.call(this, texture)) {
  40031. return true;
  40032. }
  40033. if (this._albedoTexture === texture) {
  40034. return true;
  40035. }
  40036. if (this._ambientTexture === texture) {
  40037. return true;
  40038. }
  40039. if (this._opacityTexture === texture) {
  40040. return true;
  40041. }
  40042. if (this._reflectionTexture === texture) {
  40043. return true;
  40044. }
  40045. if (this._reflectivityTexture === texture) {
  40046. return true;
  40047. }
  40048. if (this._metallicTexture === texture) {
  40049. return true;
  40050. }
  40051. if (this._microSurfaceTexture === texture) {
  40052. return true;
  40053. }
  40054. if (this._bumpTexture === texture) {
  40055. return true;
  40056. }
  40057. if (this._lightmapTexture === texture) {
  40058. return true;
  40059. }
  40060. if (this._refractionTexture === texture) {
  40061. return true;
  40062. }
  40063. return false;
  40064. };
  40065. PBRMaterial.prototype.clone = function (name) {
  40066. var _this = this;
  40067. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  40068. clone.id = name;
  40069. clone.name = name;
  40070. return clone;
  40071. };
  40072. PBRMaterial.prototype.serialize = function () {
  40073. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40074. serializationObject.customType = "BABYLON.PBRMaterial";
  40075. return serializationObject;
  40076. };
  40077. // Statics
  40078. PBRMaterial.Parse = function (source, scene, rootUrl) {
  40079. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  40080. };
  40081. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  40082. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  40083. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  40084. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  40085. __decorate([
  40086. BABYLON.serialize(),
  40087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40088. ], PBRMaterial.prototype, "directIntensity", void 0);
  40089. __decorate([
  40090. BABYLON.serialize(),
  40091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40092. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  40093. __decorate([
  40094. BABYLON.serialize(),
  40095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40096. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  40097. __decorate([
  40098. BABYLON.serialize(),
  40099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40100. ], PBRMaterial.prototype, "specularIntensity", void 0);
  40101. __decorate([
  40102. BABYLON.serialize(),
  40103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40104. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  40105. __decorate([
  40106. BABYLON.serializeAsTexture(),
  40107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40108. ], PBRMaterial.prototype, "albedoTexture", void 0);
  40109. __decorate([
  40110. BABYLON.serializeAsTexture(),
  40111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40112. ], PBRMaterial.prototype, "ambientTexture", void 0);
  40113. __decorate([
  40114. BABYLON.serialize(),
  40115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40116. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  40117. __decorate([
  40118. BABYLON.serializeAsTexture(),
  40119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40120. ], PBRMaterial.prototype, "opacityTexture", void 0);
  40121. __decorate([
  40122. BABYLON.serializeAsTexture(),
  40123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40124. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  40125. __decorate([
  40126. BABYLON.serializeAsTexture(),
  40127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40128. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  40129. __decorate([
  40130. BABYLON.serializeAsTexture(),
  40131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40132. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  40133. __decorate([
  40134. BABYLON.serializeAsTexture(),
  40135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40136. ], PBRMaterial.prototype, "metallicTexture", void 0);
  40137. __decorate([
  40138. BABYLON.serialize(),
  40139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40140. ], PBRMaterial.prototype, "metallic", void 0);
  40141. __decorate([
  40142. BABYLON.serialize(),
  40143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40144. ], PBRMaterial.prototype, "roughness", void 0);
  40145. __decorate([
  40146. BABYLON.serializeAsTexture(),
  40147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40148. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  40149. __decorate([
  40150. BABYLON.serializeAsTexture(),
  40151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40152. ], PBRMaterial.prototype, "bumpTexture", void 0);
  40153. __decorate([
  40154. BABYLON.serializeAsTexture(),
  40155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40156. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  40157. __decorate([
  40158. BABYLON.serializeAsTexture(),
  40159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40160. ], PBRMaterial.prototype, "refractionTexture", void 0);
  40161. __decorate([
  40162. BABYLON.serializeAsColor3("ambient"),
  40163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40164. ], PBRMaterial.prototype, "ambientColor", void 0);
  40165. __decorate([
  40166. BABYLON.serializeAsColor3("albedo"),
  40167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40168. ], PBRMaterial.prototype, "albedoColor", void 0);
  40169. __decorate([
  40170. BABYLON.serializeAsColor3("reflectivity"),
  40171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40172. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  40173. __decorate([
  40174. BABYLON.serializeAsColor3("reflection"),
  40175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40176. ], PBRMaterial.prototype, "reflectionColor", void 0);
  40177. __decorate([
  40178. BABYLON.serializeAsColor3("emissive"),
  40179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40180. ], PBRMaterial.prototype, "emissiveColor", void 0);
  40181. __decorate([
  40182. BABYLON.serialize(),
  40183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40184. ], PBRMaterial.prototype, "microSurface", void 0);
  40185. __decorate([
  40186. BABYLON.serialize(),
  40187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40188. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  40189. __decorate([
  40190. BABYLON.serialize(),
  40191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40192. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  40193. __decorate([
  40194. BABYLON.serialize(),
  40195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40196. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  40197. __decorate([
  40198. BABYLON.serialize(),
  40199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40200. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40201. __decorate([
  40202. BABYLON.serialize(),
  40203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40204. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40205. __decorate([
  40206. BABYLON.serialize(),
  40207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40208. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  40209. __decorate([
  40210. BABYLON.serialize(),
  40211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40212. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  40213. __decorate([
  40214. BABYLON.serialize(),
  40215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40216. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40217. __decorate([
  40218. BABYLON.serialize(),
  40219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40220. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40221. __decorate([
  40222. BABYLON.serialize(),
  40223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40224. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40225. __decorate([
  40226. BABYLON.serialize(),
  40227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40228. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40229. __decorate([
  40230. BABYLON.serialize(),
  40231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40232. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40233. __decorate([
  40234. BABYLON.serialize(),
  40235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40236. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40237. __decorate([
  40238. BABYLON.serialize(),
  40239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40240. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40241. __decorate([
  40242. BABYLON.serialize(),
  40243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40244. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40245. __decorate([
  40246. BABYLON.serialize(),
  40247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40248. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40249. __decorate([
  40250. BABYLON.serialize(),
  40251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40252. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40253. __decorate([
  40254. BABYLON.serialize(),
  40255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40256. ], PBRMaterial.prototype, "useParallax", void 0);
  40257. __decorate([
  40258. BABYLON.serialize(),
  40259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40260. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40261. __decorate([
  40262. BABYLON.serialize(),
  40263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40264. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40265. __decorate([
  40266. BABYLON.serialize(),
  40267. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40268. ], PBRMaterial.prototype, "disableLighting", void 0);
  40269. __decorate([
  40270. BABYLON.serialize(),
  40271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40272. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40273. __decorate([
  40274. BABYLON.serialize(),
  40275. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40276. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40277. __decorate([
  40278. BABYLON.serialize(),
  40279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40280. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40281. __decorate([
  40282. BABYLON.serialize(),
  40283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40284. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40285. __decorate([
  40286. BABYLON.serialize(),
  40287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40288. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40289. __decorate([
  40290. BABYLON.serialize(),
  40291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40292. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40293. __decorate([
  40294. BABYLON.serialize(),
  40295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40296. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40297. __decorate([
  40298. BABYLON.serializeAsTexture(),
  40299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40300. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40301. __decorate([
  40302. BABYLON.serialize(),
  40303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40304. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40305. __decorate([
  40306. BABYLON.serialize(),
  40307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40308. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40309. __decorate([
  40310. BABYLON.serialize(),
  40311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40312. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40313. return PBRMaterial;
  40314. }(BABYLON.PBRBaseMaterial));
  40315. BABYLON.PBRMaterial = PBRMaterial;
  40316. })(BABYLON || (BABYLON = {}));
  40317. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40318. var BABYLON;
  40319. (function (BABYLON) {
  40320. /**
  40321. * The PBR material of BJS following the metal roughness convention.
  40322. *
  40323. * This fits to the PBR convention in the GLTF definition:
  40324. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40325. */
  40326. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40327. __extends(PBRMetallicRoughnessMaterial, _super);
  40328. /**
  40329. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40330. *
  40331. * @param name The material name
  40332. * @param scene The scene the material will be use in.
  40333. */
  40334. function PBRMetallicRoughnessMaterial(name, scene) {
  40335. var _this = _super.call(this, name, scene) || this;
  40336. _this._useRoughnessFromMetallicTextureAlpha = false;
  40337. _this._useRoughnessFromMetallicTextureGreen = true;
  40338. _this._useMetallnessFromMetallicTextureBlue = true;
  40339. _this._forceMetallicWorkflow = true;
  40340. return _this;
  40341. }
  40342. /**
  40343. * Return the currrent class name of the material.
  40344. */
  40345. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40346. return "PBRMetallicRoughnessMaterial";
  40347. };
  40348. /**
  40349. * Return the active textures of the material.
  40350. */
  40351. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40352. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40353. if (this.baseTexture) {
  40354. activeTextures.push(this.baseTexture);
  40355. }
  40356. if (this.metallicRoughnessTexture) {
  40357. activeTextures.push(this.metallicRoughnessTexture);
  40358. }
  40359. return activeTextures;
  40360. };
  40361. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40362. if (_super.prototype.hasTexture.call(this, texture)) {
  40363. return true;
  40364. }
  40365. if (this.baseTexture === texture) {
  40366. return true;
  40367. }
  40368. if (this.metallicRoughnessTexture === texture) {
  40369. return true;
  40370. }
  40371. return false;
  40372. };
  40373. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40374. var _this = this;
  40375. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40376. clone.id = name;
  40377. clone.name = name;
  40378. return clone;
  40379. };
  40380. /**
  40381. * Serialize the material to a parsable JSON object.
  40382. */
  40383. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40384. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40385. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40386. return serializationObject;
  40387. };
  40388. /**
  40389. * Parses a JSON object correponding to the serialize function.
  40390. */
  40391. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40392. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40393. };
  40394. __decorate([
  40395. BABYLON.serializeAsColor3(),
  40396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40397. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40398. __decorate([
  40399. BABYLON.serializeAsTexture(),
  40400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40401. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40402. __decorate([
  40403. BABYLON.serialize(),
  40404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40405. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40406. __decorate([
  40407. BABYLON.serialize(),
  40408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40409. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40410. __decorate([
  40411. BABYLON.serializeAsTexture(),
  40412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40413. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40414. return PBRMetallicRoughnessMaterial;
  40415. }(BABYLON.PBRBaseSimpleMaterial));
  40416. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40417. })(BABYLON || (BABYLON = {}));
  40418. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40419. var BABYLON;
  40420. (function (BABYLON) {
  40421. /**
  40422. * The PBR material of BJS following the specular glossiness convention.
  40423. *
  40424. * This fits to the PBR convention in the GLTF definition:
  40425. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40426. */
  40427. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40428. __extends(PBRSpecularGlossinessMaterial, _super);
  40429. /**
  40430. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40431. *
  40432. * @param name The material name
  40433. * @param scene The scene the material will be use in.
  40434. */
  40435. function PBRSpecularGlossinessMaterial(name, scene) {
  40436. var _this = _super.call(this, name, scene) || this;
  40437. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40438. return _this;
  40439. }
  40440. /**
  40441. * Return the currrent class name of the material.
  40442. */
  40443. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40444. return "PBRSpecularGlossinessMaterial";
  40445. };
  40446. /**
  40447. * Return the active textures of the material.
  40448. */
  40449. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40450. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40451. if (this.diffuseTexture) {
  40452. activeTextures.push(this.diffuseTexture);
  40453. }
  40454. if (this.specularGlossinessTexture) {
  40455. activeTextures.push(this.specularGlossinessTexture);
  40456. }
  40457. return activeTextures;
  40458. };
  40459. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40460. if (_super.prototype.hasTexture.call(this, texture)) {
  40461. return true;
  40462. }
  40463. if (this.diffuseTexture === texture) {
  40464. return true;
  40465. }
  40466. if (this.specularGlossinessTexture === texture) {
  40467. return true;
  40468. }
  40469. return false;
  40470. };
  40471. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40472. var _this = this;
  40473. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40474. clone.id = name;
  40475. clone.name = name;
  40476. return clone;
  40477. };
  40478. /**
  40479. * Serialize the material to a parsable JSON object.
  40480. */
  40481. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40482. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40483. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40484. return serializationObject;
  40485. };
  40486. /**
  40487. * Parses a JSON object correponding to the serialize function.
  40488. */
  40489. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40490. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40491. };
  40492. __decorate([
  40493. BABYLON.serializeAsColor3("diffuse"),
  40494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40495. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40496. __decorate([
  40497. BABYLON.serializeAsTexture(),
  40498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40499. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40500. __decorate([
  40501. BABYLON.serializeAsColor3("specular"),
  40502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40503. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40504. __decorate([
  40505. BABYLON.serialize(),
  40506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40507. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40508. __decorate([
  40509. BABYLON.serializeAsTexture(),
  40510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40511. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40512. return PBRSpecularGlossinessMaterial;
  40513. }(BABYLON.PBRBaseSimpleMaterial));
  40514. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40515. })(BABYLON || (BABYLON = {}));
  40516. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40517. var BABYLON;
  40518. (function (BABYLON) {
  40519. BABYLON.CameraInputTypes = {};
  40520. var CameraInputsManager = /** @class */ (function () {
  40521. function CameraInputsManager(camera) {
  40522. this.attached = {};
  40523. this.camera = camera;
  40524. this.checkInputs = function () { };
  40525. }
  40526. /**
  40527. * Add an input method to a camera.
  40528. * builtin inputs example: camera.inputs.addGamepad();
  40529. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40530. * @param input camera input method
  40531. */
  40532. CameraInputsManager.prototype.add = function (input) {
  40533. var type = input.getSimpleName();
  40534. if (this.attached[type]) {
  40535. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40536. return;
  40537. }
  40538. this.attached[type] = input;
  40539. input.camera = this.camera;
  40540. //for checkInputs, we are dynamically creating a function
  40541. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40542. if (input.checkInputs) {
  40543. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40544. }
  40545. if (this.attachedElement) {
  40546. input.attachControl(this.attachedElement);
  40547. }
  40548. };
  40549. /**
  40550. * Remove a specific input method from a camera
  40551. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40552. * @param inputToRemove camera input method
  40553. */
  40554. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40555. for (var cam in this.attached) {
  40556. var input = this.attached[cam];
  40557. if (input === inputToRemove) {
  40558. input.detachControl(this.attachedElement);
  40559. input.camera = null;
  40560. delete this.attached[cam];
  40561. this.rebuildInputCheck();
  40562. }
  40563. }
  40564. };
  40565. CameraInputsManager.prototype.removeByType = function (inputType) {
  40566. for (var cam in this.attached) {
  40567. var input = this.attached[cam];
  40568. if (input.getClassName() === inputType) {
  40569. input.detachControl(this.attachedElement);
  40570. input.camera = null;
  40571. delete this.attached[cam];
  40572. this.rebuildInputCheck();
  40573. }
  40574. }
  40575. };
  40576. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40577. var current = this.checkInputs;
  40578. return function () {
  40579. current();
  40580. fn();
  40581. };
  40582. };
  40583. CameraInputsManager.prototype.attachInput = function (input) {
  40584. if (this.attachedElement) {
  40585. input.attachControl(this.attachedElement, this.noPreventDefault);
  40586. }
  40587. };
  40588. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40589. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40590. if (this.attachedElement) {
  40591. return;
  40592. }
  40593. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40594. this.attachedElement = element;
  40595. this.noPreventDefault = noPreventDefault;
  40596. for (var cam in this.attached) {
  40597. this.attached[cam].attachControl(element, noPreventDefault);
  40598. }
  40599. };
  40600. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40601. if (disconnect === void 0) { disconnect = false; }
  40602. if (this.attachedElement !== element) {
  40603. return;
  40604. }
  40605. for (var cam in this.attached) {
  40606. this.attached[cam].detachControl(element);
  40607. if (disconnect) {
  40608. this.attached[cam].camera = null;
  40609. }
  40610. }
  40611. this.attachedElement = null;
  40612. };
  40613. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40614. this.checkInputs = function () { };
  40615. for (var cam in this.attached) {
  40616. var input = this.attached[cam];
  40617. if (input.checkInputs) {
  40618. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40619. }
  40620. }
  40621. };
  40622. /**
  40623. * Remove all attached input methods from a camera
  40624. */
  40625. CameraInputsManager.prototype.clear = function () {
  40626. if (this.attachedElement) {
  40627. this.detachElement(this.attachedElement, true);
  40628. }
  40629. this.attached = {};
  40630. this.attachedElement = null;
  40631. this.checkInputs = function () { };
  40632. };
  40633. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40634. var inputs = {};
  40635. for (var cam in this.attached) {
  40636. var input = this.attached[cam];
  40637. var res = BABYLON.SerializationHelper.Serialize(input);
  40638. inputs[input.getClassName()] = res;
  40639. }
  40640. serializedCamera.inputsmgr = inputs;
  40641. };
  40642. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40643. var parsedInputs = parsedCamera.inputsmgr;
  40644. if (parsedInputs) {
  40645. this.clear();
  40646. for (var n in parsedInputs) {
  40647. var construct = BABYLON.CameraInputTypes[n];
  40648. if (construct) {
  40649. var parsedinput = parsedInputs[n];
  40650. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40651. this.add(input);
  40652. }
  40653. }
  40654. }
  40655. else {
  40656. //2016-03-08 this part is for managing backward compatibility
  40657. for (var n in this.attached) {
  40658. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40659. if (construct) {
  40660. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40661. this.remove(this.attached[n]);
  40662. this.add(input);
  40663. }
  40664. }
  40665. }
  40666. };
  40667. return CameraInputsManager;
  40668. }());
  40669. BABYLON.CameraInputsManager = CameraInputsManager;
  40670. })(BABYLON || (BABYLON = {}));
  40671. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40672. var BABYLON;
  40673. (function (BABYLON) {
  40674. var TargetCamera = /** @class */ (function (_super) {
  40675. __extends(TargetCamera, _super);
  40676. function TargetCamera(name, position, scene) {
  40677. var _this = _super.call(this, name, position, scene) || this;
  40678. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40679. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40680. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40681. _this.speed = 2.0;
  40682. _this.noRotationConstraint = false;
  40683. _this.lockedTarget = null;
  40684. _this._currentTarget = BABYLON.Vector3.Zero();
  40685. _this._viewMatrix = BABYLON.Matrix.Zero();
  40686. _this._camMatrix = BABYLON.Matrix.Zero();
  40687. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40688. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40689. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40690. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40691. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40692. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40693. _this._tempMatrix = BABYLON.Matrix.Zero();
  40694. return _this;
  40695. }
  40696. TargetCamera.prototype.getFrontPosition = function (distance) {
  40697. this.getWorldMatrix();
  40698. var direction = this.getTarget().subtract(this.position);
  40699. direction.normalize();
  40700. direction.scaleInPlace(distance);
  40701. return this.globalPosition.add(direction);
  40702. };
  40703. TargetCamera.prototype._getLockedTargetPosition = function () {
  40704. if (!this.lockedTarget) {
  40705. return null;
  40706. }
  40707. if (this.lockedTarget.absolutePosition) {
  40708. this.lockedTarget.computeWorldMatrix();
  40709. }
  40710. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40711. };
  40712. TargetCamera.prototype.storeState = function () {
  40713. this._storedPosition = this.position.clone();
  40714. this._storedRotation = this.rotation.clone();
  40715. if (this.rotationQuaternion) {
  40716. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40717. }
  40718. return _super.prototype.storeState.call(this);
  40719. };
  40720. /**
  40721. * Restored camera state. You must call storeState() first
  40722. */
  40723. TargetCamera.prototype._restoreStateValues = function () {
  40724. if (!_super.prototype._restoreStateValues.call(this)) {
  40725. return false;
  40726. }
  40727. this.position = this._storedPosition.clone();
  40728. this.rotation = this._storedRotation.clone();
  40729. if (this.rotationQuaternion) {
  40730. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40731. }
  40732. this.cameraDirection.copyFromFloats(0, 0, 0);
  40733. this.cameraRotation.copyFromFloats(0, 0);
  40734. return true;
  40735. };
  40736. // Cache
  40737. TargetCamera.prototype._initCache = function () {
  40738. _super.prototype._initCache.call(this);
  40739. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40740. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40741. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40742. };
  40743. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40744. if (!ignoreParentClass) {
  40745. _super.prototype._updateCache.call(this);
  40746. }
  40747. var lockedTargetPosition = this._getLockedTargetPosition();
  40748. if (!lockedTargetPosition) {
  40749. this._cache.lockedTarget = null;
  40750. }
  40751. else {
  40752. if (!this._cache.lockedTarget) {
  40753. this._cache.lockedTarget = lockedTargetPosition.clone();
  40754. }
  40755. else {
  40756. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40757. }
  40758. }
  40759. this._cache.rotation.copyFrom(this.rotation);
  40760. if (this.rotationQuaternion)
  40761. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40762. };
  40763. // Synchronized
  40764. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40765. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40766. return false;
  40767. }
  40768. var lockedTargetPosition = this._getLockedTargetPosition();
  40769. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40770. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40771. };
  40772. // Methods
  40773. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40774. var engine = this.getEngine();
  40775. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40776. };
  40777. // Target
  40778. TargetCamera.prototype.setTarget = function (target) {
  40779. this.upVector.normalize();
  40780. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40781. this._camMatrix.invert();
  40782. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40783. var vDir = target.subtract(this.position);
  40784. if (vDir.x >= 0.0) {
  40785. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40786. }
  40787. else {
  40788. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40789. }
  40790. this.rotation.z = 0;
  40791. if (isNaN(this.rotation.x)) {
  40792. this.rotation.x = 0;
  40793. }
  40794. if (isNaN(this.rotation.y)) {
  40795. this.rotation.y = 0;
  40796. }
  40797. if (isNaN(this.rotation.z)) {
  40798. this.rotation.z = 0;
  40799. }
  40800. if (this.rotationQuaternion) {
  40801. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40802. }
  40803. };
  40804. /**
  40805. * Return the current target position of the camera. This value is expressed in local space.
  40806. */
  40807. TargetCamera.prototype.getTarget = function () {
  40808. return this._currentTarget;
  40809. };
  40810. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40811. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40812. };
  40813. TargetCamera.prototype._updatePosition = function () {
  40814. if (this.parent) {
  40815. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40816. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40817. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40818. return;
  40819. }
  40820. this.position.addInPlace(this.cameraDirection);
  40821. };
  40822. TargetCamera.prototype._checkInputs = function () {
  40823. var needToMove = this._decideIfNeedsToMove();
  40824. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40825. // Move
  40826. if (needToMove) {
  40827. this._updatePosition();
  40828. }
  40829. // Rotate
  40830. if (needToRotate) {
  40831. this.rotation.x += this.cameraRotation.x;
  40832. this.rotation.y += this.cameraRotation.y;
  40833. //rotate, if quaternion is set and rotation was used
  40834. if (this.rotationQuaternion) {
  40835. var len = this.rotation.lengthSquared();
  40836. if (len) {
  40837. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40838. }
  40839. }
  40840. if (!this.noRotationConstraint) {
  40841. var limit = (Math.PI / 2) * 0.95;
  40842. if (this.rotation.x > limit)
  40843. this.rotation.x = limit;
  40844. if (this.rotation.x < -limit)
  40845. this.rotation.x = -limit;
  40846. }
  40847. }
  40848. // Inertia
  40849. if (needToMove) {
  40850. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40851. this.cameraDirection.x = 0;
  40852. }
  40853. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40854. this.cameraDirection.y = 0;
  40855. }
  40856. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40857. this.cameraDirection.z = 0;
  40858. }
  40859. this.cameraDirection.scaleInPlace(this.inertia);
  40860. }
  40861. if (needToRotate) {
  40862. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40863. this.cameraRotation.x = 0;
  40864. }
  40865. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40866. this.cameraRotation.y = 0;
  40867. }
  40868. this.cameraRotation.scaleInPlace(this.inertia);
  40869. }
  40870. _super.prototype._checkInputs.call(this);
  40871. };
  40872. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40873. if (this.rotationQuaternion) {
  40874. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40875. }
  40876. else {
  40877. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40878. }
  40879. //update the up vector!
  40880. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40881. };
  40882. TargetCamera.prototype._getViewMatrix = function () {
  40883. if (this.lockedTarget) {
  40884. this.setTarget(this._getLockedTargetPosition());
  40885. }
  40886. // Compute
  40887. this._updateCameraRotationMatrix();
  40888. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40889. // Computing target and final matrix
  40890. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40891. if (this.getScene().useRightHandedSystem) {
  40892. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40893. }
  40894. else {
  40895. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40896. }
  40897. return this._viewMatrix;
  40898. };
  40899. /**
  40900. * @override
  40901. * Override Camera.createRigCamera
  40902. */
  40903. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40904. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40905. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40906. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40907. if (!this.rotationQuaternion) {
  40908. this.rotationQuaternion = new BABYLON.Quaternion();
  40909. }
  40910. rigCamera._cameraRigParams = {};
  40911. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40912. }
  40913. return rigCamera;
  40914. }
  40915. return null;
  40916. };
  40917. /**
  40918. * @override
  40919. * Override Camera._updateRigCameras
  40920. */
  40921. TargetCamera.prototype._updateRigCameras = function () {
  40922. var camLeft = this._rigCameras[0];
  40923. var camRight = this._rigCameras[1];
  40924. switch (this.cameraRigMode) {
  40925. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40926. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40929. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40930. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40931. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40932. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40933. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40934. camLeft.setTarget(this.getTarget());
  40935. camRight.setTarget(this.getTarget());
  40936. break;
  40937. case BABYLON.Camera.RIG_MODE_VR:
  40938. if (camLeft.rotationQuaternion) {
  40939. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40940. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40941. }
  40942. else {
  40943. camLeft.rotation.copyFrom(this.rotation);
  40944. camRight.rotation.copyFrom(this.rotation);
  40945. }
  40946. camLeft.position.copyFrom(this.position);
  40947. camRight.position.copyFrom(this.position);
  40948. break;
  40949. }
  40950. _super.prototype._updateRigCameras.call(this);
  40951. };
  40952. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40953. if (!this._rigCamTransformMatrix) {
  40954. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40955. }
  40956. var target = this.getTarget();
  40957. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40958. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40959. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40960. };
  40961. TargetCamera.prototype.getClassName = function () {
  40962. return "TargetCamera";
  40963. };
  40964. __decorate([
  40965. BABYLON.serializeAsVector3()
  40966. ], TargetCamera.prototype, "rotation", void 0);
  40967. __decorate([
  40968. BABYLON.serialize()
  40969. ], TargetCamera.prototype, "speed", void 0);
  40970. __decorate([
  40971. BABYLON.serializeAsMeshReference("lockedTargetId")
  40972. ], TargetCamera.prototype, "lockedTarget", void 0);
  40973. return TargetCamera;
  40974. }(BABYLON.Camera));
  40975. BABYLON.TargetCamera = TargetCamera;
  40976. })(BABYLON || (BABYLON = {}));
  40977. //# sourceMappingURL=babylon.targetCamera.js.map
  40978. var BABYLON;
  40979. (function (BABYLON) {
  40980. var FreeCameraMouseInput = /** @class */ (function () {
  40981. function FreeCameraMouseInput(touchEnabled) {
  40982. if (touchEnabled === void 0) { touchEnabled = true; }
  40983. this.touchEnabled = touchEnabled;
  40984. this.buttons = [0, 1, 2];
  40985. this.angularSensibility = 2000.0;
  40986. this.previousPosition = null;
  40987. }
  40988. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40989. var _this = this;
  40990. var engine = this.camera.getEngine();
  40991. if (!this._pointerInput) {
  40992. this._pointerInput = function (p, s) {
  40993. var evt = p.event;
  40994. if (engine.isInVRExclusivePointerMode) {
  40995. return;
  40996. }
  40997. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40998. return;
  40999. }
  41000. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41001. return;
  41002. }
  41003. var srcElement = (evt.srcElement || evt.target);
  41004. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41005. try {
  41006. srcElement.setPointerCapture(evt.pointerId);
  41007. }
  41008. catch (e) {
  41009. //Nothing to do with the error. Execution will continue.
  41010. }
  41011. _this.previousPosition = {
  41012. x: evt.clientX,
  41013. y: evt.clientY
  41014. };
  41015. if (!noPreventDefault) {
  41016. evt.preventDefault();
  41017. element.focus();
  41018. }
  41019. }
  41020. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41021. try {
  41022. srcElement.releasePointerCapture(evt.pointerId);
  41023. }
  41024. catch (e) {
  41025. //Nothing to do with the error.
  41026. }
  41027. _this.previousPosition = null;
  41028. if (!noPreventDefault) {
  41029. evt.preventDefault();
  41030. }
  41031. }
  41032. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41033. if (!_this.previousPosition || engine.isPointerLock) {
  41034. return;
  41035. }
  41036. var offsetX = evt.clientX - _this.previousPosition.x;
  41037. var offsetY = evt.clientY - _this.previousPosition.y;
  41038. if (_this.camera.getScene().useRightHandedSystem) {
  41039. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41040. }
  41041. else {
  41042. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41043. }
  41044. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41045. _this.previousPosition = {
  41046. x: evt.clientX,
  41047. y: evt.clientY
  41048. };
  41049. if (!noPreventDefault) {
  41050. evt.preventDefault();
  41051. }
  41052. }
  41053. };
  41054. }
  41055. this._onMouseMove = function (evt) {
  41056. if (!engine.isPointerLock) {
  41057. return;
  41058. }
  41059. if (engine.isInVRExclusivePointerMode) {
  41060. return;
  41061. }
  41062. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41063. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41064. if (_this.camera.getScene().useRightHandedSystem) {
  41065. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41066. }
  41067. else {
  41068. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41069. }
  41070. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41071. _this.previousPosition = null;
  41072. if (!noPreventDefault) {
  41073. evt.preventDefault();
  41074. }
  41075. };
  41076. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  41077. element.addEventListener("mousemove", this._onMouseMove, false);
  41078. };
  41079. FreeCameraMouseInput.prototype.detachControl = function (element) {
  41080. if (this._observer && element) {
  41081. this.camera.getScene().onPointerObservable.remove(this._observer);
  41082. if (this._onMouseMove) {
  41083. element.removeEventListener("mousemove", this._onMouseMove);
  41084. }
  41085. this._observer = null;
  41086. this._onMouseMove = null;
  41087. this.previousPosition = null;
  41088. }
  41089. };
  41090. FreeCameraMouseInput.prototype.getClassName = function () {
  41091. return "FreeCameraMouseInput";
  41092. };
  41093. FreeCameraMouseInput.prototype.getSimpleName = function () {
  41094. return "mouse";
  41095. };
  41096. __decorate([
  41097. BABYLON.serialize()
  41098. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  41099. __decorate([
  41100. BABYLON.serialize()
  41101. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  41102. return FreeCameraMouseInput;
  41103. }());
  41104. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  41105. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  41106. })(BABYLON || (BABYLON = {}));
  41107. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  41108. var BABYLON;
  41109. (function (BABYLON) {
  41110. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  41111. function FreeCameraKeyboardMoveInput() {
  41112. this._keys = new Array();
  41113. this.keysUp = [38];
  41114. this.keysDown = [40];
  41115. this.keysLeft = [37];
  41116. this.keysRight = [39];
  41117. }
  41118. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41119. var _this = this;
  41120. if (this._onCanvasBlurObserver) {
  41121. return;
  41122. }
  41123. this._scene = this.camera.getScene();
  41124. this._engine = this._scene.getEngine();
  41125. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41126. _this._keys = [];
  41127. });
  41128. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41129. var evt = info.event;
  41130. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41131. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41132. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41133. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41134. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41135. var index = _this._keys.indexOf(evt.keyCode);
  41136. if (index === -1) {
  41137. _this._keys.push(evt.keyCode);
  41138. }
  41139. if (!noPreventDefault) {
  41140. evt.preventDefault();
  41141. }
  41142. }
  41143. }
  41144. else {
  41145. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41146. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41147. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41148. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41149. var index = _this._keys.indexOf(evt.keyCode);
  41150. if (index >= 0) {
  41151. _this._keys.splice(index, 1);
  41152. }
  41153. if (!noPreventDefault) {
  41154. evt.preventDefault();
  41155. }
  41156. }
  41157. }
  41158. });
  41159. };
  41160. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41161. if (this._scene) {
  41162. if (this._onKeyboardObserver) {
  41163. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41164. }
  41165. if (this._onCanvasBlurObserver) {
  41166. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41167. }
  41168. this._onKeyboardObserver = null;
  41169. this._onCanvasBlurObserver = null;
  41170. }
  41171. this._keys = [];
  41172. };
  41173. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41174. if (this._onKeyboardObserver) {
  41175. var camera = this.camera;
  41176. // Keyboard
  41177. for (var index = 0; index < this._keys.length; index++) {
  41178. var keyCode = this._keys[index];
  41179. var speed = camera._computeLocalCameraSpeed();
  41180. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41181. camera._localDirection.copyFromFloats(-speed, 0, 0);
  41182. }
  41183. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41184. camera._localDirection.copyFromFloats(0, 0, speed);
  41185. }
  41186. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41187. camera._localDirection.copyFromFloats(speed, 0, 0);
  41188. }
  41189. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41190. camera._localDirection.copyFromFloats(0, 0, -speed);
  41191. }
  41192. if (camera.getScene().useRightHandedSystem) {
  41193. camera._localDirection.z *= -1;
  41194. }
  41195. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  41196. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  41197. camera.cameraDirection.addInPlace(camera._transformedDirection);
  41198. }
  41199. }
  41200. };
  41201. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  41202. return "FreeCameraKeyboardMoveInput";
  41203. };
  41204. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  41205. this._keys = [];
  41206. };
  41207. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41208. return "keyboard";
  41209. };
  41210. __decorate([
  41211. BABYLON.serialize()
  41212. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41213. __decorate([
  41214. BABYLON.serialize()
  41215. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41216. __decorate([
  41217. BABYLON.serialize()
  41218. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41219. __decorate([
  41220. BABYLON.serialize()
  41221. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41222. return FreeCameraKeyboardMoveInput;
  41223. }());
  41224. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  41225. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  41226. })(BABYLON || (BABYLON = {}));
  41227. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  41228. var BABYLON;
  41229. (function (BABYLON) {
  41230. var FreeCameraInputsManager = /** @class */ (function (_super) {
  41231. __extends(FreeCameraInputsManager, _super);
  41232. function FreeCameraInputsManager(camera) {
  41233. return _super.call(this, camera) || this;
  41234. }
  41235. FreeCameraInputsManager.prototype.addKeyboard = function () {
  41236. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  41237. return this;
  41238. };
  41239. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  41240. if (touchEnabled === void 0) { touchEnabled = true; }
  41241. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  41242. return this;
  41243. };
  41244. FreeCameraInputsManager.prototype.addGamepad = function () {
  41245. this.add(new BABYLON.FreeCameraGamepadInput());
  41246. return this;
  41247. };
  41248. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  41249. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  41250. return this;
  41251. };
  41252. FreeCameraInputsManager.prototype.addTouch = function () {
  41253. this.add(new BABYLON.FreeCameraTouchInput());
  41254. return this;
  41255. };
  41256. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  41257. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  41258. return this;
  41259. };
  41260. return FreeCameraInputsManager;
  41261. }(BABYLON.CameraInputsManager));
  41262. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  41263. })(BABYLON || (BABYLON = {}));
  41264. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  41265. var BABYLON;
  41266. (function (BABYLON) {
  41267. var FreeCamera = /** @class */ (function (_super) {
  41268. __extends(FreeCamera, _super);
  41269. function FreeCamera(name, position, scene) {
  41270. var _this = _super.call(this, name, position, scene) || this;
  41271. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41272. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41273. _this.checkCollisions = false;
  41274. _this.applyGravity = false;
  41275. _this._needMoveForGravity = false;
  41276. _this._oldPosition = BABYLON.Vector3.Zero();
  41277. _this._diffPosition = BABYLON.Vector3.Zero();
  41278. _this._newPosition = BABYLON.Vector3.Zero();
  41279. // Collisions
  41280. _this._collisionMask = -1;
  41281. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41282. if (collidedMesh === void 0) { collidedMesh = null; }
  41283. //TODO move this to the collision coordinator!
  41284. if (_this.getScene().workerCollisions)
  41285. newPosition.multiplyInPlace(_this._collider._radius);
  41286. var updatePosition = function (newPos) {
  41287. _this._newPosition.copyFrom(newPos);
  41288. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41289. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41290. _this.position.addInPlace(_this._diffPosition);
  41291. if (_this.onCollide && collidedMesh) {
  41292. _this.onCollide(collidedMesh);
  41293. }
  41294. }
  41295. };
  41296. updatePosition(newPosition);
  41297. };
  41298. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41299. _this.inputs.addKeyboard().addMouse();
  41300. return _this;
  41301. }
  41302. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41303. //-- begin properties for backward compatibility for inputs
  41304. /**
  41305. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41306. * Higher values reduce sensitivity.
  41307. */
  41308. get: function () {
  41309. var mouse = this.inputs.attached["mouse"];
  41310. if (mouse)
  41311. return mouse.angularSensibility;
  41312. return 0;
  41313. },
  41314. /**
  41315. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41316. * Higher values reduce sensitivity.
  41317. */
  41318. set: function (value) {
  41319. var mouse = this.inputs.attached["mouse"];
  41320. if (mouse)
  41321. mouse.angularSensibility = value;
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41327. get: function () {
  41328. var keyboard = this.inputs.attached["keyboard"];
  41329. if (keyboard)
  41330. return keyboard.keysUp;
  41331. return [];
  41332. },
  41333. set: function (value) {
  41334. var keyboard = this.inputs.attached["keyboard"];
  41335. if (keyboard)
  41336. keyboard.keysUp = value;
  41337. },
  41338. enumerable: true,
  41339. configurable: true
  41340. });
  41341. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41342. get: function () {
  41343. var keyboard = this.inputs.attached["keyboard"];
  41344. if (keyboard)
  41345. return keyboard.keysDown;
  41346. return [];
  41347. },
  41348. set: function (value) {
  41349. var keyboard = this.inputs.attached["keyboard"];
  41350. if (keyboard)
  41351. keyboard.keysDown = value;
  41352. },
  41353. enumerable: true,
  41354. configurable: true
  41355. });
  41356. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41357. get: function () {
  41358. var keyboard = this.inputs.attached["keyboard"];
  41359. if (keyboard)
  41360. return keyboard.keysLeft;
  41361. return [];
  41362. },
  41363. set: function (value) {
  41364. var keyboard = this.inputs.attached["keyboard"];
  41365. if (keyboard)
  41366. keyboard.keysLeft = value;
  41367. },
  41368. enumerable: true,
  41369. configurable: true
  41370. });
  41371. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41372. get: function () {
  41373. var keyboard = this.inputs.attached["keyboard"];
  41374. if (keyboard)
  41375. return keyboard.keysRight;
  41376. return [];
  41377. },
  41378. set: function (value) {
  41379. var keyboard = this.inputs.attached["keyboard"];
  41380. if (keyboard)
  41381. keyboard.keysRight = value;
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. // Controls
  41387. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41388. this.inputs.attachElement(element, noPreventDefault);
  41389. };
  41390. FreeCamera.prototype.detachControl = function (element) {
  41391. this.inputs.detachElement(element);
  41392. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41393. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41394. };
  41395. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41396. get: function () {
  41397. return this._collisionMask;
  41398. },
  41399. set: function (mask) {
  41400. this._collisionMask = !isNaN(mask) ? mask : -1;
  41401. },
  41402. enumerable: true,
  41403. configurable: true
  41404. });
  41405. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41406. var globalPosition;
  41407. if (this.parent) {
  41408. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41409. }
  41410. else {
  41411. globalPosition = this.position;
  41412. }
  41413. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41414. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41415. if (!this._collider) {
  41416. this._collider = new BABYLON.Collider();
  41417. }
  41418. this._collider._radius = this.ellipsoid;
  41419. this._collider.collisionMask = this._collisionMask;
  41420. //no need for clone, as long as gravity is not on.
  41421. var actualDisplacement = displacement;
  41422. //add gravity to the direction to prevent the dual-collision checking
  41423. if (this.applyGravity) {
  41424. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41425. actualDisplacement = displacement.add(this.getScene().gravity);
  41426. }
  41427. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41428. };
  41429. FreeCamera.prototype._checkInputs = function () {
  41430. if (!this._localDirection) {
  41431. this._localDirection = BABYLON.Vector3.Zero();
  41432. this._transformedDirection = BABYLON.Vector3.Zero();
  41433. }
  41434. this.inputs.checkInputs();
  41435. _super.prototype._checkInputs.call(this);
  41436. };
  41437. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41438. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41439. };
  41440. FreeCamera.prototype._updatePosition = function () {
  41441. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41442. this._collideWithWorld(this.cameraDirection);
  41443. }
  41444. else {
  41445. _super.prototype._updatePosition.call(this);
  41446. }
  41447. };
  41448. FreeCamera.prototype.dispose = function () {
  41449. this.inputs.clear();
  41450. _super.prototype.dispose.call(this);
  41451. };
  41452. FreeCamera.prototype.getClassName = function () {
  41453. return "FreeCamera";
  41454. };
  41455. __decorate([
  41456. BABYLON.serializeAsVector3()
  41457. ], FreeCamera.prototype, "ellipsoid", void 0);
  41458. __decorate([
  41459. BABYLON.serializeAsVector3()
  41460. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41461. __decorate([
  41462. BABYLON.serialize()
  41463. ], FreeCamera.prototype, "checkCollisions", void 0);
  41464. __decorate([
  41465. BABYLON.serialize()
  41466. ], FreeCamera.prototype, "applyGravity", void 0);
  41467. return FreeCamera;
  41468. }(BABYLON.TargetCamera));
  41469. BABYLON.FreeCamera = FreeCamera;
  41470. })(BABYLON || (BABYLON = {}));
  41471. //# sourceMappingURL=babylon.freeCamera.js.map
  41472. var BABYLON;
  41473. (function (BABYLON) {
  41474. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41475. function ArcRotateCameraKeyboardMoveInput() {
  41476. this._keys = new Array();
  41477. this.keysUp = [38];
  41478. this.keysDown = [40];
  41479. this.keysLeft = [37];
  41480. this.keysRight = [39];
  41481. this.keysReset = [220];
  41482. this.panningSensibility = 50.0;
  41483. this.zoomingSensibility = 25.0;
  41484. this.useAltToZoom = true;
  41485. }
  41486. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41487. var _this = this;
  41488. if (this._onCanvasBlurObserver) {
  41489. return;
  41490. }
  41491. this._scene = this.camera.getScene();
  41492. this._engine = this._scene.getEngine();
  41493. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41494. _this._keys = [];
  41495. });
  41496. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41497. var evt = info.event;
  41498. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41499. _this._ctrlPressed = evt.ctrlKey;
  41500. _this._altPressed = evt.altKey;
  41501. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41502. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41503. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41504. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41505. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41506. var index = _this._keys.indexOf(evt.keyCode);
  41507. if (index === -1) {
  41508. _this._keys.push(evt.keyCode);
  41509. }
  41510. if (evt.preventDefault) {
  41511. if (!noPreventDefault) {
  41512. evt.preventDefault();
  41513. }
  41514. }
  41515. }
  41516. }
  41517. else {
  41518. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41519. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41520. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41521. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41522. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41523. var index = _this._keys.indexOf(evt.keyCode);
  41524. if (index >= 0) {
  41525. _this._keys.splice(index, 1);
  41526. }
  41527. if (evt.preventDefault) {
  41528. if (!noPreventDefault) {
  41529. evt.preventDefault();
  41530. }
  41531. }
  41532. }
  41533. }
  41534. });
  41535. };
  41536. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41537. if (this._scene) {
  41538. if (this._onKeyboardObserver) {
  41539. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41540. }
  41541. if (this._onCanvasBlurObserver) {
  41542. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41543. }
  41544. this._onKeyboardObserver = null;
  41545. this._onCanvasBlurObserver = null;
  41546. }
  41547. this._keys = [];
  41548. };
  41549. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41550. if (this._onKeyboardObserver) {
  41551. var camera = this.camera;
  41552. for (var index = 0; index < this._keys.length; index++) {
  41553. var keyCode = this._keys[index];
  41554. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41555. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41556. camera.inertialPanningX -= 1 / this.panningSensibility;
  41557. }
  41558. else {
  41559. camera.inertialAlphaOffset -= 0.01;
  41560. }
  41561. }
  41562. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41563. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41564. camera.inertialPanningY += 1 / this.panningSensibility;
  41565. }
  41566. else if (this._altPressed && this.useAltToZoom) {
  41567. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41568. }
  41569. else {
  41570. camera.inertialBetaOffset -= 0.01;
  41571. }
  41572. }
  41573. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41574. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41575. camera.inertialPanningX += 1 / this.panningSensibility;
  41576. }
  41577. else {
  41578. camera.inertialAlphaOffset += 0.01;
  41579. }
  41580. }
  41581. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41582. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41583. camera.inertialPanningY -= 1 / this.panningSensibility;
  41584. }
  41585. else if (this._altPressed && this.useAltToZoom) {
  41586. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41587. }
  41588. else {
  41589. camera.inertialBetaOffset += 0.01;
  41590. }
  41591. }
  41592. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41593. camera.restoreState();
  41594. }
  41595. }
  41596. }
  41597. };
  41598. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41599. return "ArcRotateCameraKeyboardMoveInput";
  41600. };
  41601. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41602. return "keyboard";
  41603. };
  41604. __decorate([
  41605. BABYLON.serialize()
  41606. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41607. __decorate([
  41608. BABYLON.serialize()
  41609. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41610. __decorate([
  41611. BABYLON.serialize()
  41612. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41613. __decorate([
  41614. BABYLON.serialize()
  41615. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41616. __decorate([
  41617. BABYLON.serialize()
  41618. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41619. __decorate([
  41620. BABYLON.serialize()
  41621. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41622. __decorate([
  41623. BABYLON.serialize()
  41624. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41625. __decorate([
  41626. BABYLON.serialize()
  41627. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41628. return ArcRotateCameraKeyboardMoveInput;
  41629. }());
  41630. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41631. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41632. })(BABYLON || (BABYLON = {}));
  41633. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41634. var BABYLON;
  41635. (function (BABYLON) {
  41636. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41637. function ArcRotateCameraMouseWheelInput() {
  41638. this.wheelPrecision = 3.0;
  41639. /**
  41640. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41641. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41642. */
  41643. this.wheelDeltaPercentage = 0;
  41644. }
  41645. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41646. var _this = this;
  41647. this._wheel = function (p, s) {
  41648. //sanity check - this should be a PointerWheel event.
  41649. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41650. return;
  41651. var event = p.event;
  41652. var delta = 0;
  41653. if (event.wheelDelta) {
  41654. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41655. }
  41656. else if (event.detail) {
  41657. delta = -event.detail / _this.wheelPrecision;
  41658. }
  41659. if (delta)
  41660. _this.camera.inertialRadiusOffset += delta;
  41661. if (event.preventDefault) {
  41662. if (!noPreventDefault) {
  41663. event.preventDefault();
  41664. }
  41665. }
  41666. };
  41667. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41668. };
  41669. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41670. if (this._observer && element) {
  41671. this.camera.getScene().onPointerObservable.remove(this._observer);
  41672. this._observer = null;
  41673. this._wheel = null;
  41674. }
  41675. };
  41676. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41677. return "ArcRotateCameraMouseWheelInput";
  41678. };
  41679. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41680. return "mousewheel";
  41681. };
  41682. __decorate([
  41683. BABYLON.serialize()
  41684. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41685. __decorate([
  41686. BABYLON.serialize()
  41687. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41688. return ArcRotateCameraMouseWheelInput;
  41689. }());
  41690. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41691. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41692. })(BABYLON || (BABYLON = {}));
  41693. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41694. var BABYLON;
  41695. (function (BABYLON) {
  41696. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41697. function ArcRotateCameraPointersInput() {
  41698. this.buttons = [0, 1, 2];
  41699. this.angularSensibilityX = 1000.0;
  41700. this.angularSensibilityY = 1000.0;
  41701. this.pinchPrecision = 12.0;
  41702. /**
  41703. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41704. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41705. */
  41706. this.pinchDeltaPercentage = 0;
  41707. this.panningSensibility = 1000.0;
  41708. this.multiTouchPanning = true;
  41709. this.multiTouchPanAndZoom = true;
  41710. this._isPanClick = false;
  41711. this.pinchInwards = true;
  41712. }
  41713. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41714. var _this = this;
  41715. var engine = this.camera.getEngine();
  41716. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41717. var pointA = null;
  41718. var pointB = null;
  41719. var previousPinchSquaredDistance = 0;
  41720. var initialDistance = 0;
  41721. var twoFingerActivityCount = 0;
  41722. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41723. this._pointerInput = function (p, s) {
  41724. var evt = p.event;
  41725. var isTouch = p.event.pointerType === "touch";
  41726. if (engine.isInVRExclusivePointerMode) {
  41727. return;
  41728. }
  41729. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41730. return;
  41731. }
  41732. var srcElement = (evt.srcElement || evt.target);
  41733. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41734. try {
  41735. srcElement.setPointerCapture(evt.pointerId);
  41736. }
  41737. catch (e) {
  41738. //Nothing to do with the error. Execution will continue.
  41739. }
  41740. // Manage panning with pan button click
  41741. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41742. // manage pointers
  41743. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41744. if (pointA === null) {
  41745. pointA = cacheSoloPointer;
  41746. }
  41747. else if (pointB === null) {
  41748. pointB = cacheSoloPointer;
  41749. }
  41750. if (!noPreventDefault) {
  41751. evt.preventDefault();
  41752. element.focus();
  41753. }
  41754. }
  41755. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41756. _this.camera.restoreState();
  41757. }
  41758. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41759. try {
  41760. srcElement.releasePointerCapture(evt.pointerId);
  41761. }
  41762. catch (e) {
  41763. //Nothing to do with the error.
  41764. }
  41765. cacheSoloPointer = null;
  41766. previousPinchSquaredDistance = 0;
  41767. previousMultiTouchPanPosition.isPaning = false;
  41768. previousMultiTouchPanPosition.isPinching = false;
  41769. twoFingerActivityCount = 0;
  41770. initialDistance = 0;
  41771. if (!isTouch) {
  41772. pointB = null; // Mouse and pen are mono pointer
  41773. }
  41774. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41775. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41776. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41777. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41778. if (engine.badOS) {
  41779. pointA = pointB = null;
  41780. }
  41781. else {
  41782. //only remove the impacted pointer in case of multitouch allowing on most
  41783. //platforms switching from rotate to zoom and pan seamlessly.
  41784. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41785. pointA = pointB;
  41786. pointB = null;
  41787. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41788. }
  41789. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41790. pointB = null;
  41791. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41792. }
  41793. else {
  41794. pointA = pointB = null;
  41795. }
  41796. }
  41797. if (!noPreventDefault) {
  41798. evt.preventDefault();
  41799. }
  41800. }
  41801. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41802. if (!noPreventDefault) {
  41803. evt.preventDefault();
  41804. }
  41805. // One button down
  41806. if (pointA && pointB === null && cacheSoloPointer) {
  41807. if (_this.panningSensibility !== 0 &&
  41808. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41809. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41810. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41811. }
  41812. else {
  41813. var offsetX = evt.clientX - cacheSoloPointer.x;
  41814. var offsetY = evt.clientY - cacheSoloPointer.y;
  41815. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41816. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41817. }
  41818. cacheSoloPointer.x = evt.clientX;
  41819. cacheSoloPointer.y = evt.clientY;
  41820. }
  41821. else if (pointA && pointB) {
  41822. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41823. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41824. ed.x = evt.clientX;
  41825. ed.y = evt.clientY;
  41826. var direction = _this.pinchInwards ? 1 : -1;
  41827. var distX = pointA.x - pointB.x;
  41828. var distY = pointA.y - pointB.y;
  41829. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41830. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41831. if (previousPinchSquaredDistance === 0) {
  41832. initialDistance = pinchDistance;
  41833. previousPinchSquaredDistance = pinchSquaredDistance;
  41834. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41835. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41836. return;
  41837. }
  41838. if (_this.multiTouchPanAndZoom) {
  41839. if (_this.pinchDeltaPercentage) {
  41840. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41841. }
  41842. else {
  41843. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41844. (_this.pinchPrecision *
  41845. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41846. direction);
  41847. }
  41848. if (_this.panningSensibility !== 0) {
  41849. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41850. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41851. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41852. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41853. previousMultiTouchPanPosition.x = pointersCenterX;
  41854. previousMultiTouchPanPosition.y = pointersCenterY;
  41855. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41856. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41857. }
  41858. }
  41859. else {
  41860. twoFingerActivityCount++;
  41861. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41862. if (_this.pinchDeltaPercentage) {
  41863. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41864. }
  41865. else {
  41866. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41867. (_this.pinchPrecision *
  41868. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41869. direction);
  41870. }
  41871. previousMultiTouchPanPosition.isPaning = false;
  41872. previousMultiTouchPanPosition.isPinching = true;
  41873. }
  41874. else {
  41875. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41876. if (!previousMultiTouchPanPosition.isPaning) {
  41877. previousMultiTouchPanPosition.isPaning = true;
  41878. previousMultiTouchPanPosition.isPinching = false;
  41879. previousMultiTouchPanPosition.x = ed.x;
  41880. previousMultiTouchPanPosition.y = ed.y;
  41881. return;
  41882. }
  41883. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41884. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41885. }
  41886. }
  41887. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41888. previousMultiTouchPanPosition.x = ed.x;
  41889. previousMultiTouchPanPosition.y = ed.y;
  41890. }
  41891. }
  41892. previousPinchSquaredDistance = pinchSquaredDistance;
  41893. }
  41894. }
  41895. };
  41896. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41897. this._onContextMenu = function (evt) {
  41898. evt.preventDefault();
  41899. };
  41900. if (!this.camera._useCtrlForPanning) {
  41901. element.addEventListener("contextmenu", this._onContextMenu, false);
  41902. }
  41903. this._onLostFocus = function () {
  41904. //this._keys = [];
  41905. pointA = pointB = null;
  41906. previousPinchSquaredDistance = 0;
  41907. previousMultiTouchPanPosition.isPaning = false;
  41908. previousMultiTouchPanPosition.isPinching = false;
  41909. twoFingerActivityCount = 0;
  41910. cacheSoloPointer = null;
  41911. initialDistance = 0;
  41912. };
  41913. this._onMouseMove = function (evt) {
  41914. if (!engine.isPointerLock) {
  41915. return;
  41916. }
  41917. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41918. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41919. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41920. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41921. if (!noPreventDefault) {
  41922. evt.preventDefault();
  41923. }
  41924. };
  41925. this._onGestureStart = function (e) {
  41926. if (window.MSGesture === undefined) {
  41927. return;
  41928. }
  41929. if (!_this._MSGestureHandler) {
  41930. _this._MSGestureHandler = new MSGesture();
  41931. _this._MSGestureHandler.target = element;
  41932. }
  41933. _this._MSGestureHandler.addPointer(e.pointerId);
  41934. };
  41935. this._onGesture = function (e) {
  41936. _this.camera.radius *= e.scale;
  41937. if (e.preventDefault) {
  41938. if (!noPreventDefault) {
  41939. e.stopPropagation();
  41940. e.preventDefault();
  41941. }
  41942. }
  41943. };
  41944. element.addEventListener("mousemove", this._onMouseMove, false);
  41945. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41946. element.addEventListener("MSGestureChange", this._onGesture, false);
  41947. BABYLON.Tools.RegisterTopRootEvents([
  41948. { name: "blur", handler: this._onLostFocus }
  41949. ]);
  41950. };
  41951. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41952. if (this._onLostFocus) {
  41953. BABYLON.Tools.UnregisterTopRootEvents([
  41954. { name: "blur", handler: this._onLostFocus }
  41955. ]);
  41956. }
  41957. if (element && this._observer) {
  41958. this.camera.getScene().onPointerObservable.remove(this._observer);
  41959. this._observer = null;
  41960. if (this._onContextMenu) {
  41961. element.removeEventListener("contextmenu", this._onContextMenu);
  41962. }
  41963. if (this._onMouseMove) {
  41964. element.removeEventListener("mousemove", this._onMouseMove);
  41965. }
  41966. if (this._onGestureStart) {
  41967. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41968. }
  41969. if (this._onGesture) {
  41970. element.removeEventListener("MSGestureChange", this._onGesture);
  41971. }
  41972. this._isPanClick = false;
  41973. this.pinchInwards = true;
  41974. this._onMouseMove = null;
  41975. this._onGestureStart = null;
  41976. this._onGesture = null;
  41977. this._MSGestureHandler = null;
  41978. this._onLostFocus = null;
  41979. this._onContextMenu = null;
  41980. }
  41981. };
  41982. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41983. return "ArcRotateCameraPointersInput";
  41984. };
  41985. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41986. return "pointers";
  41987. };
  41988. __decorate([
  41989. BABYLON.serialize()
  41990. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41991. __decorate([
  41992. BABYLON.serialize()
  41993. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41994. __decorate([
  41995. BABYLON.serialize()
  41996. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41997. __decorate([
  41998. BABYLON.serialize()
  41999. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  42000. __decorate([
  42001. BABYLON.serialize()
  42002. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  42003. __decorate([
  42004. BABYLON.serialize()
  42005. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  42006. __decorate([
  42007. BABYLON.serialize()
  42008. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  42009. __decorate([
  42010. BABYLON.serialize()
  42011. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  42012. return ArcRotateCameraPointersInput;
  42013. }());
  42014. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  42015. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  42016. })(BABYLON || (BABYLON = {}));
  42017. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  42018. var BABYLON;
  42019. (function (BABYLON) {
  42020. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  42021. __extends(ArcRotateCameraInputsManager, _super);
  42022. function ArcRotateCameraInputsManager(camera) {
  42023. return _super.call(this, camera) || this;
  42024. }
  42025. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  42026. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  42027. return this;
  42028. };
  42029. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  42030. this.add(new BABYLON.ArcRotateCameraPointersInput());
  42031. return this;
  42032. };
  42033. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  42034. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  42035. return this;
  42036. };
  42037. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  42038. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  42039. return this;
  42040. };
  42041. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  42042. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  42043. return this;
  42044. };
  42045. return ArcRotateCameraInputsManager;
  42046. }(BABYLON.CameraInputsManager));
  42047. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  42048. })(BABYLON || (BABYLON = {}));
  42049. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  42050. var BABYLON;
  42051. (function (BABYLON) {
  42052. var ArcRotateCamera = /** @class */ (function (_super) {
  42053. __extends(ArcRotateCamera, _super);
  42054. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  42055. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  42056. _this.inertialAlphaOffset = 0;
  42057. _this.inertialBetaOffset = 0;
  42058. _this.inertialRadiusOffset = 0;
  42059. _this.lowerAlphaLimit = null;
  42060. _this.upperAlphaLimit = null;
  42061. _this.lowerBetaLimit = 0.01;
  42062. _this.upperBetaLimit = Math.PI;
  42063. _this.lowerRadiusLimit = null;
  42064. _this.upperRadiusLimit = null;
  42065. _this.inertialPanningX = 0;
  42066. _this.inertialPanningY = 0;
  42067. _this.pinchToPanMaxDistance = 20;
  42068. _this.panningDistanceLimit = null;
  42069. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  42070. _this.panningInertia = 0.9;
  42071. //-- end properties for backward compatibility for inputs
  42072. _this.zoomOnFactor = 1;
  42073. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  42074. _this.allowUpsideDown = true;
  42075. _this._viewMatrix = new BABYLON.Matrix();
  42076. // Panning
  42077. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  42078. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  42079. _this.checkCollisions = false;
  42080. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42081. _this._previousPosition = BABYLON.Vector3.Zero();
  42082. _this._collisionVelocity = BABYLON.Vector3.Zero();
  42083. _this._newPosition = BABYLON.Vector3.Zero();
  42084. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42085. if (collidedMesh === void 0) { collidedMesh = null; }
  42086. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  42087. newPosition.multiplyInPlace(_this._collider._radius);
  42088. }
  42089. if (!collidedMesh) {
  42090. _this._previousPosition.copyFrom(_this.position);
  42091. }
  42092. else {
  42093. _this.setPosition(newPosition);
  42094. if (_this.onCollide) {
  42095. _this.onCollide(collidedMesh);
  42096. }
  42097. }
  42098. // Recompute because of constraints
  42099. var cosa = Math.cos(_this.alpha);
  42100. var sina = Math.sin(_this.alpha);
  42101. var cosb = Math.cos(_this.beta);
  42102. var sinb = Math.sin(_this.beta);
  42103. if (sinb === 0) {
  42104. sinb = 0.0001;
  42105. }
  42106. var target = _this._getTargetPosition();
  42107. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  42108. _this.position.copyFrom(_this._newPosition);
  42109. var up = _this.upVector;
  42110. if (_this.allowUpsideDown && _this.beta < 0) {
  42111. up = up.clone();
  42112. up = up.negate();
  42113. }
  42114. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  42115. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  42116. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  42117. _this._collisionTriggered = false;
  42118. };
  42119. _this._target = BABYLON.Vector3.Zero();
  42120. if (target) {
  42121. _this.setTarget(target);
  42122. }
  42123. _this.alpha = alpha;
  42124. _this.beta = beta;
  42125. _this.radius = radius;
  42126. _this.getViewMatrix();
  42127. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  42128. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  42129. return _this;
  42130. }
  42131. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  42132. get: function () {
  42133. return this._target;
  42134. },
  42135. set: function (value) {
  42136. this.setTarget(value);
  42137. },
  42138. enumerable: true,
  42139. configurable: true
  42140. });
  42141. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  42142. //-- begin properties for backward compatibility for inputs
  42143. get: function () {
  42144. var pointers = this.inputs.attached["pointers"];
  42145. if (pointers)
  42146. return pointers.angularSensibilityX;
  42147. return 0;
  42148. },
  42149. set: function (value) {
  42150. var pointers = this.inputs.attached["pointers"];
  42151. if (pointers) {
  42152. pointers.angularSensibilityX = value;
  42153. }
  42154. },
  42155. enumerable: true,
  42156. configurable: true
  42157. });
  42158. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  42159. get: function () {
  42160. var pointers = this.inputs.attached["pointers"];
  42161. if (pointers)
  42162. return pointers.angularSensibilityY;
  42163. return 0;
  42164. },
  42165. set: function (value) {
  42166. var pointers = this.inputs.attached["pointers"];
  42167. if (pointers) {
  42168. pointers.angularSensibilityY = value;
  42169. }
  42170. },
  42171. enumerable: true,
  42172. configurable: true
  42173. });
  42174. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  42175. get: function () {
  42176. var pointers = this.inputs.attached["pointers"];
  42177. if (pointers)
  42178. return pointers.pinchPrecision;
  42179. return 0;
  42180. },
  42181. set: function (value) {
  42182. var pointers = this.inputs.attached["pointers"];
  42183. if (pointers) {
  42184. pointers.pinchPrecision = value;
  42185. }
  42186. },
  42187. enumerable: true,
  42188. configurable: true
  42189. });
  42190. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  42191. get: function () {
  42192. var pointers = this.inputs.attached["pointers"];
  42193. if (pointers)
  42194. return pointers.pinchDeltaPercentage;
  42195. return 0;
  42196. },
  42197. set: function (value) {
  42198. var pointers = this.inputs.attached["pointers"];
  42199. if (pointers) {
  42200. pointers.pinchDeltaPercentage = value;
  42201. }
  42202. },
  42203. enumerable: true,
  42204. configurable: true
  42205. });
  42206. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  42207. get: function () {
  42208. var pointers = this.inputs.attached["pointers"];
  42209. if (pointers)
  42210. return pointers.panningSensibility;
  42211. return 0;
  42212. },
  42213. set: function (value) {
  42214. var pointers = this.inputs.attached["pointers"];
  42215. if (pointers) {
  42216. pointers.panningSensibility = value;
  42217. }
  42218. },
  42219. enumerable: true,
  42220. configurable: true
  42221. });
  42222. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  42223. get: function () {
  42224. var keyboard = this.inputs.attached["keyboard"];
  42225. if (keyboard)
  42226. return keyboard.keysUp;
  42227. return [];
  42228. },
  42229. set: function (value) {
  42230. var keyboard = this.inputs.attached["keyboard"];
  42231. if (keyboard)
  42232. keyboard.keysUp = value;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  42238. get: function () {
  42239. var keyboard = this.inputs.attached["keyboard"];
  42240. if (keyboard)
  42241. return keyboard.keysDown;
  42242. return [];
  42243. },
  42244. set: function (value) {
  42245. var keyboard = this.inputs.attached["keyboard"];
  42246. if (keyboard)
  42247. keyboard.keysDown = value;
  42248. },
  42249. enumerable: true,
  42250. configurable: true
  42251. });
  42252. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  42253. get: function () {
  42254. var keyboard = this.inputs.attached["keyboard"];
  42255. if (keyboard)
  42256. return keyboard.keysLeft;
  42257. return [];
  42258. },
  42259. set: function (value) {
  42260. var keyboard = this.inputs.attached["keyboard"];
  42261. if (keyboard)
  42262. keyboard.keysLeft = value;
  42263. },
  42264. enumerable: true,
  42265. configurable: true
  42266. });
  42267. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  42268. get: function () {
  42269. var keyboard = this.inputs.attached["keyboard"];
  42270. if (keyboard)
  42271. return keyboard.keysRight;
  42272. return [];
  42273. },
  42274. set: function (value) {
  42275. var keyboard = this.inputs.attached["keyboard"];
  42276. if (keyboard)
  42277. keyboard.keysRight = value;
  42278. },
  42279. enumerable: true,
  42280. configurable: true
  42281. });
  42282. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42283. get: function () {
  42284. var mousewheel = this.inputs.attached["mousewheel"];
  42285. if (mousewheel)
  42286. return mousewheel.wheelPrecision;
  42287. return 0;
  42288. },
  42289. set: function (value) {
  42290. var mousewheel = this.inputs.attached["mousewheel"];
  42291. if (mousewheel)
  42292. mousewheel.wheelPrecision = value;
  42293. },
  42294. enumerable: true,
  42295. configurable: true
  42296. });
  42297. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42298. get: function () {
  42299. var mousewheel = this.inputs.attached["mousewheel"];
  42300. if (mousewheel)
  42301. return mousewheel.wheelDeltaPercentage;
  42302. return 0;
  42303. },
  42304. set: function (value) {
  42305. var mousewheel = this.inputs.attached["mousewheel"];
  42306. if (mousewheel)
  42307. mousewheel.wheelDeltaPercentage = value;
  42308. },
  42309. enumerable: true,
  42310. configurable: true
  42311. });
  42312. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42313. get: function () {
  42314. return this._bouncingBehavior;
  42315. },
  42316. enumerable: true,
  42317. configurable: true
  42318. });
  42319. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42320. get: function () {
  42321. return this._bouncingBehavior != null;
  42322. },
  42323. set: function (value) {
  42324. if (value === this.useBouncingBehavior) {
  42325. return;
  42326. }
  42327. if (value) {
  42328. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42329. this.addBehavior(this._bouncingBehavior);
  42330. }
  42331. else if (this._bouncingBehavior) {
  42332. this.removeBehavior(this._bouncingBehavior);
  42333. this._bouncingBehavior = null;
  42334. }
  42335. },
  42336. enumerable: true,
  42337. configurable: true
  42338. });
  42339. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42340. get: function () {
  42341. return this._framingBehavior;
  42342. },
  42343. enumerable: true,
  42344. configurable: true
  42345. });
  42346. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42347. get: function () {
  42348. return this._framingBehavior != null;
  42349. },
  42350. set: function (value) {
  42351. if (value === this.useFramingBehavior) {
  42352. return;
  42353. }
  42354. if (value) {
  42355. this._framingBehavior = new BABYLON.FramingBehavior();
  42356. this.addBehavior(this._framingBehavior);
  42357. }
  42358. else if (this._framingBehavior) {
  42359. this.removeBehavior(this._framingBehavior);
  42360. this._framingBehavior = null;
  42361. }
  42362. },
  42363. enumerable: true,
  42364. configurable: true
  42365. });
  42366. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42367. get: function () {
  42368. return this._autoRotationBehavior;
  42369. },
  42370. enumerable: true,
  42371. configurable: true
  42372. });
  42373. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42374. get: function () {
  42375. return this._autoRotationBehavior != null;
  42376. },
  42377. set: function (value) {
  42378. if (value === this.useAutoRotationBehavior) {
  42379. return;
  42380. }
  42381. if (value) {
  42382. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42383. this.addBehavior(this._autoRotationBehavior);
  42384. }
  42385. else if (this._autoRotationBehavior) {
  42386. this.removeBehavior(this._autoRotationBehavior);
  42387. this._autoRotationBehavior = null;
  42388. }
  42389. },
  42390. enumerable: true,
  42391. configurable: true
  42392. });
  42393. // Cache
  42394. ArcRotateCamera.prototype._initCache = function () {
  42395. _super.prototype._initCache.call(this);
  42396. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42397. this._cache.alpha = undefined;
  42398. this._cache.beta = undefined;
  42399. this._cache.radius = undefined;
  42400. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42401. };
  42402. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42403. if (!ignoreParentClass) {
  42404. _super.prototype._updateCache.call(this);
  42405. }
  42406. this._cache._target.copyFrom(this._getTargetPosition());
  42407. this._cache.alpha = this.alpha;
  42408. this._cache.beta = this.beta;
  42409. this._cache.radius = this.radius;
  42410. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42411. };
  42412. ArcRotateCamera.prototype._getTargetPosition = function () {
  42413. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42414. var pos = this._targetHost.getAbsolutePosition();
  42415. if (this._targetBoundingCenter) {
  42416. pos.addToRef(this._targetBoundingCenter, this._target);
  42417. }
  42418. else {
  42419. this._target.copyFrom(pos);
  42420. }
  42421. }
  42422. var lockedTargetPosition = this._getLockedTargetPosition();
  42423. if (lockedTargetPosition) {
  42424. return lockedTargetPosition;
  42425. }
  42426. return this._target;
  42427. };
  42428. ArcRotateCamera.prototype.storeState = function () {
  42429. this._storedAlpha = this.alpha;
  42430. this._storedBeta = this.beta;
  42431. this._storedRadius = this.radius;
  42432. this._storedTarget = this._getTargetPosition().clone();
  42433. return _super.prototype.storeState.call(this);
  42434. };
  42435. /**
  42436. * Restored camera state. You must call storeState() first
  42437. */
  42438. ArcRotateCamera.prototype._restoreStateValues = function () {
  42439. if (!_super.prototype._restoreStateValues.call(this)) {
  42440. return false;
  42441. }
  42442. this.alpha = this._storedAlpha;
  42443. this.beta = this._storedBeta;
  42444. this.radius = this._storedRadius;
  42445. this.setTarget(this._storedTarget.clone());
  42446. this.inertialAlphaOffset = 0;
  42447. this.inertialBetaOffset = 0;
  42448. this.inertialRadiusOffset = 0;
  42449. this.inertialPanningX = 0;
  42450. this.inertialPanningY = 0;
  42451. return true;
  42452. };
  42453. // Synchronized
  42454. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42455. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42456. return false;
  42457. return this._cache._target.equals(this._getTargetPosition())
  42458. && this._cache.alpha === this.alpha
  42459. && this._cache.beta === this.beta
  42460. && this._cache.radius === this.radius
  42461. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42462. };
  42463. // Methods
  42464. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42465. var _this = this;
  42466. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42467. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42468. this._useCtrlForPanning = useCtrlForPanning;
  42469. this._panningMouseButton = panningMouseButton;
  42470. this.inputs.attachElement(element, noPreventDefault);
  42471. this._reset = function () {
  42472. _this.inertialAlphaOffset = 0;
  42473. _this.inertialBetaOffset = 0;
  42474. _this.inertialRadiusOffset = 0;
  42475. _this.inertialPanningX = 0;
  42476. _this.inertialPanningY = 0;
  42477. };
  42478. };
  42479. ArcRotateCamera.prototype.detachControl = function (element) {
  42480. this.inputs.detachElement(element);
  42481. if (this._reset) {
  42482. this._reset();
  42483. }
  42484. };
  42485. ArcRotateCamera.prototype._checkInputs = function () {
  42486. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42487. if (this._collisionTriggered) {
  42488. return;
  42489. }
  42490. this.inputs.checkInputs();
  42491. // Inertia
  42492. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42493. if (this.getScene().useRightHandedSystem) {
  42494. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42495. }
  42496. else {
  42497. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42498. }
  42499. this.beta += this.inertialBetaOffset;
  42500. this.radius -= this.inertialRadiusOffset;
  42501. this.inertialAlphaOffset *= this.inertia;
  42502. this.inertialBetaOffset *= this.inertia;
  42503. this.inertialRadiusOffset *= this.inertia;
  42504. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42505. this.inertialAlphaOffset = 0;
  42506. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42507. this.inertialBetaOffset = 0;
  42508. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42509. this.inertialRadiusOffset = 0;
  42510. }
  42511. // Panning inertia
  42512. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42513. if (!this._localDirection) {
  42514. this._localDirection = BABYLON.Vector3.Zero();
  42515. this._transformedDirection = BABYLON.Vector3.Zero();
  42516. }
  42517. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42518. this._localDirection.multiplyInPlace(this.panningAxis);
  42519. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42520. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42521. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42522. if (!this.panningAxis.y) {
  42523. this._transformedDirection.y = 0;
  42524. }
  42525. if (!this._targetHost) {
  42526. if (this.panningDistanceLimit) {
  42527. this._transformedDirection.addInPlace(this._target);
  42528. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42529. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42530. this._target.copyFrom(this._transformedDirection);
  42531. }
  42532. }
  42533. else {
  42534. this._target.addInPlace(this._transformedDirection);
  42535. }
  42536. }
  42537. this.inertialPanningX *= this.panningInertia;
  42538. this.inertialPanningY *= this.panningInertia;
  42539. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42540. this.inertialPanningX = 0;
  42541. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42542. this.inertialPanningY = 0;
  42543. }
  42544. // Limits
  42545. this._checkLimits();
  42546. _super.prototype._checkInputs.call(this);
  42547. };
  42548. ArcRotateCamera.prototype._checkLimits = function () {
  42549. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42550. if (this.allowUpsideDown && this.beta > Math.PI) {
  42551. this.beta = this.beta - (2 * Math.PI);
  42552. }
  42553. }
  42554. else {
  42555. if (this.beta < this.lowerBetaLimit) {
  42556. this.beta = this.lowerBetaLimit;
  42557. }
  42558. }
  42559. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42560. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42561. this.beta = this.beta + (2 * Math.PI);
  42562. }
  42563. }
  42564. else {
  42565. if (this.beta > this.upperBetaLimit) {
  42566. this.beta = this.upperBetaLimit;
  42567. }
  42568. }
  42569. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42570. this.alpha = this.lowerAlphaLimit;
  42571. }
  42572. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42573. this.alpha = this.upperAlphaLimit;
  42574. }
  42575. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42576. this.radius = this.lowerRadiusLimit;
  42577. }
  42578. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42579. this.radius = this.upperRadiusLimit;
  42580. }
  42581. };
  42582. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42583. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42584. this.radius = radiusv3.length();
  42585. if (this.radius === 0) {
  42586. this.radius = 0.0001; // Just to avoid division by zero
  42587. }
  42588. // Alpha
  42589. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42590. if (radiusv3.z < 0) {
  42591. this.alpha = 2 * Math.PI - this.alpha;
  42592. }
  42593. // Beta
  42594. this.beta = Math.acos(radiusv3.y / this.radius);
  42595. this._checkLimits();
  42596. };
  42597. ArcRotateCamera.prototype.setPosition = function (position) {
  42598. if (this.position.equals(position)) {
  42599. return;
  42600. }
  42601. this.position.copyFrom(position);
  42602. this.rebuildAnglesAndRadius();
  42603. };
  42604. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42605. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42606. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42607. if (target.getBoundingInfo) {
  42608. if (toBoundingCenter) {
  42609. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42610. }
  42611. else {
  42612. this._targetBoundingCenter = null;
  42613. }
  42614. this._targetHost = target;
  42615. this._target = this._getTargetPosition();
  42616. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42617. }
  42618. else {
  42619. var newTarget = target;
  42620. var currentTarget = this._getTargetPosition();
  42621. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42622. return;
  42623. }
  42624. this._targetHost = null;
  42625. this._target = newTarget;
  42626. this._targetBoundingCenter = null;
  42627. this.onMeshTargetChangedObservable.notifyObservers(null);
  42628. }
  42629. this.rebuildAnglesAndRadius();
  42630. };
  42631. ArcRotateCamera.prototype._getViewMatrix = function () {
  42632. // Compute
  42633. var cosa = Math.cos(this.alpha);
  42634. var sina = Math.sin(this.alpha);
  42635. var cosb = Math.cos(this.beta);
  42636. var sinb = Math.sin(this.beta);
  42637. if (sinb === 0) {
  42638. sinb = 0.0001;
  42639. }
  42640. var target = this._getTargetPosition();
  42641. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42642. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42643. if (!this._collider) {
  42644. this._collider = new BABYLON.Collider();
  42645. }
  42646. this._collider._radius = this.collisionRadius;
  42647. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42648. this._collisionTriggered = true;
  42649. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42650. }
  42651. else {
  42652. this.position.copyFrom(this._newPosition);
  42653. var up = this.upVector;
  42654. if (this.allowUpsideDown && sinb < 0) {
  42655. up = up.clone();
  42656. up = up.negate();
  42657. }
  42658. if (this.getScene().useRightHandedSystem) {
  42659. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42660. }
  42661. else {
  42662. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42663. }
  42664. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42665. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42666. }
  42667. this._currentTarget = target;
  42668. return this._viewMatrix;
  42669. };
  42670. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42671. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42672. meshes = meshes || this.getScene().meshes;
  42673. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42674. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42675. this.radius = distance * this.zoomOnFactor;
  42676. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42677. };
  42678. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42679. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42680. var meshesOrMinMaxVector;
  42681. var distance;
  42682. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42683. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42684. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42685. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42686. }
  42687. else {
  42688. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42689. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42690. distance = minMaxVectorAndDistance.distance;
  42691. }
  42692. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42693. if (!doNotUpdateMaxZ) {
  42694. this.maxZ = distance * 2;
  42695. }
  42696. };
  42697. /**
  42698. * @override
  42699. * Override Camera.createRigCamera
  42700. */
  42701. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42702. var alphaShift = 0;
  42703. switch (this.cameraRigMode) {
  42704. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42705. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42706. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42707. case BABYLON.Camera.RIG_MODE_VR:
  42708. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42709. break;
  42710. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42711. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42712. break;
  42713. }
  42714. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42715. rigCam._cameraRigParams = {};
  42716. return rigCam;
  42717. };
  42718. /**
  42719. * @override
  42720. * Override Camera._updateRigCameras
  42721. */
  42722. ArcRotateCamera.prototype._updateRigCameras = function () {
  42723. var camLeft = this._rigCameras[0];
  42724. var camRight = this._rigCameras[1];
  42725. camLeft.beta = camRight.beta = this.beta;
  42726. camLeft.radius = camRight.radius = this.radius;
  42727. switch (this.cameraRigMode) {
  42728. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42729. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42730. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42731. case BABYLON.Camera.RIG_MODE_VR:
  42732. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42733. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42734. break;
  42735. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42736. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42737. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42738. break;
  42739. }
  42740. _super.prototype._updateRigCameras.call(this);
  42741. };
  42742. ArcRotateCamera.prototype.dispose = function () {
  42743. this.inputs.clear();
  42744. _super.prototype.dispose.call(this);
  42745. };
  42746. ArcRotateCamera.prototype.getClassName = function () {
  42747. return "ArcRotateCamera";
  42748. };
  42749. __decorate([
  42750. BABYLON.serialize()
  42751. ], ArcRotateCamera.prototype, "alpha", void 0);
  42752. __decorate([
  42753. BABYLON.serialize()
  42754. ], ArcRotateCamera.prototype, "beta", void 0);
  42755. __decorate([
  42756. BABYLON.serialize()
  42757. ], ArcRotateCamera.prototype, "radius", void 0);
  42758. __decorate([
  42759. BABYLON.serializeAsVector3("target")
  42760. ], ArcRotateCamera.prototype, "_target", void 0);
  42761. __decorate([
  42762. BABYLON.serialize()
  42763. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42764. __decorate([
  42765. BABYLON.serialize()
  42766. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42767. __decorate([
  42768. BABYLON.serialize()
  42769. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42770. __decorate([
  42771. BABYLON.serialize()
  42772. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42773. __decorate([
  42774. BABYLON.serialize()
  42775. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42776. __decorate([
  42777. BABYLON.serialize()
  42778. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42779. __decorate([
  42780. BABYLON.serialize()
  42781. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42782. __decorate([
  42783. BABYLON.serialize()
  42784. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42785. __decorate([
  42786. BABYLON.serialize()
  42787. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42788. __decorate([
  42789. BABYLON.serialize()
  42790. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42791. __decorate([
  42792. BABYLON.serialize()
  42793. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42794. __decorate([
  42795. BABYLON.serialize()
  42796. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42797. __decorate([
  42798. BABYLON.serialize()
  42799. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42800. __decorate([
  42801. BABYLON.serializeAsVector3()
  42802. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42803. __decorate([
  42804. BABYLON.serialize()
  42805. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42806. __decorate([
  42807. BABYLON.serialize()
  42808. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42809. __decorate([
  42810. BABYLON.serialize()
  42811. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42812. return ArcRotateCamera;
  42813. }(BABYLON.TargetCamera));
  42814. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42815. })(BABYLON || (BABYLON = {}));
  42816. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42817. var BABYLON;
  42818. (function (BABYLON) {
  42819. /**
  42820. * The HemisphericLight simulates the ambient environment light,
  42821. * so the passed direction is the light reflection direction, not the incoming direction.
  42822. */
  42823. var HemisphericLight = /** @class */ (function (_super) {
  42824. __extends(HemisphericLight, _super);
  42825. /**
  42826. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42827. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42828. * The HemisphericLight can't cast shadows.
  42829. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42830. * @param name The friendly name of the light
  42831. * @param direction The direction of the light reflection
  42832. * @param scene The scene the light belongs to
  42833. */
  42834. function HemisphericLight(name, direction, scene) {
  42835. var _this = _super.call(this, name, scene) || this;
  42836. /**
  42837. * The groundColor is the light in the opposite direction to the one specified during creation.
  42838. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  42839. */
  42840. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42841. _this.direction = direction || BABYLON.Vector3.Up();
  42842. return _this;
  42843. }
  42844. HemisphericLight.prototype._buildUniformLayout = function () {
  42845. this._uniformBuffer.addUniform("vLightData", 4);
  42846. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42847. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42848. this._uniformBuffer.addUniform("vLightGround", 3);
  42849. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42850. this._uniformBuffer.addUniform("depthValues", 2);
  42851. this._uniformBuffer.create();
  42852. };
  42853. /**
  42854. * Returns the string "HemisphericLight".
  42855. * @return The class name
  42856. */
  42857. HemisphericLight.prototype.getClassName = function () {
  42858. return "HemisphericLight";
  42859. };
  42860. /**
  42861. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42862. * Returns the updated direction.
  42863. * @param target The target the direction should point to
  42864. * @return The computed direction
  42865. */
  42866. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42867. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42868. return this.direction;
  42869. };
  42870. /**
  42871. * Returns the shadow generator associated to the light.
  42872. * @returns Always null for hemispheric lights because it does not support shadows.
  42873. */
  42874. HemisphericLight.prototype.getShadowGenerator = function () {
  42875. return null;
  42876. };
  42877. /**
  42878. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42879. * @param effect The effect to update
  42880. * @param lightIndex The index of the light in the effect to update
  42881. * @returns The hemispheric light
  42882. */
  42883. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42884. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42885. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42886. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42887. return this;
  42888. };
  42889. /**
  42890. * @ignore internal use only.
  42891. */
  42892. HemisphericLight.prototype._getWorldMatrix = function () {
  42893. if (!this._worldMatrix) {
  42894. this._worldMatrix = BABYLON.Matrix.Identity();
  42895. }
  42896. return this._worldMatrix;
  42897. };
  42898. /**
  42899. * Returns the integer 3.
  42900. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  42901. */
  42902. HemisphericLight.prototype.getTypeID = function () {
  42903. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42904. };
  42905. __decorate([
  42906. BABYLON.serializeAsColor3()
  42907. ], HemisphericLight.prototype, "groundColor", void 0);
  42908. __decorate([
  42909. BABYLON.serializeAsVector3()
  42910. ], HemisphericLight.prototype, "direction", void 0);
  42911. return HemisphericLight;
  42912. }(BABYLON.Light));
  42913. BABYLON.HemisphericLight = HemisphericLight;
  42914. })(BABYLON || (BABYLON = {}));
  42915. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42916. var BABYLON;
  42917. (function (BABYLON) {
  42918. /**
  42919. * Base implementation of @see IShadowLight
  42920. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  42921. */
  42922. var ShadowLight = /** @class */ (function (_super) {
  42923. __extends(ShadowLight, _super);
  42924. function ShadowLight() {
  42925. var _this = _super !== null && _super.apply(this, arguments) || this;
  42926. _this._needProjectionMatrixCompute = true;
  42927. return _this;
  42928. }
  42929. Object.defineProperty(ShadowLight.prototype, "direction", {
  42930. get: function () {
  42931. return this._direction;
  42932. },
  42933. /**
  42934. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  42935. */
  42936. set: function (value) {
  42937. this._direction = value;
  42938. },
  42939. enumerable: true,
  42940. configurable: true
  42941. });
  42942. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42943. /**
  42944. * Gets the shadow projection clipping minimum z value.
  42945. */
  42946. get: function () {
  42947. return this._shadowMinZ;
  42948. },
  42949. /**
  42950. * Sets the shadow projection clipping minimum z value.
  42951. */
  42952. set: function (value) {
  42953. this._shadowMinZ = value;
  42954. this.forceProjectionMatrixCompute();
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42960. /**
  42961. * Sets the shadow projection clipping maximum z value.
  42962. */
  42963. get: function () {
  42964. return this._shadowMaxZ;
  42965. },
  42966. /**
  42967. * Gets the shadow projection clipping maximum z value.
  42968. */
  42969. set: function (value) {
  42970. this._shadowMaxZ = value;
  42971. this.forceProjectionMatrixCompute();
  42972. },
  42973. enumerable: true,
  42974. configurable: true
  42975. });
  42976. /**
  42977. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  42978. * @returns true if the information has been computed, false if it does not need to (no parenting)
  42979. */
  42980. ShadowLight.prototype.computeTransformedInformation = function () {
  42981. if (this.parent && this.parent.getWorldMatrix) {
  42982. if (!this.transformedPosition) {
  42983. this.transformedPosition = BABYLON.Vector3.Zero();
  42984. }
  42985. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42986. // In case the direction is present.
  42987. if (this.direction) {
  42988. if (!this.transformedDirection) {
  42989. this.transformedDirection = BABYLON.Vector3.Zero();
  42990. }
  42991. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42992. }
  42993. return true;
  42994. }
  42995. return false;
  42996. };
  42997. /**
  42998. * Return the depth scale used for the shadow map.
  42999. * @returns the depth scale.
  43000. */
  43001. ShadowLight.prototype.getDepthScale = function () {
  43002. return 50.0;
  43003. };
  43004. /**
  43005. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  43006. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43007. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43008. */
  43009. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  43010. return this.transformedDirection ? this.transformedDirection : this.direction;
  43011. };
  43012. /**
  43013. * Returns the ShadowLight absolute position in the World.
  43014. * @returns the position vector in world space
  43015. */
  43016. ShadowLight.prototype.getAbsolutePosition = function () {
  43017. return this.transformedPosition ? this.transformedPosition : this.position;
  43018. };
  43019. /**
  43020. * Sets the ShadowLight direction toward the passed target.
  43021. * @param target The point tot target in local space
  43022. * @returns the updated ShadowLight direction
  43023. */
  43024. ShadowLight.prototype.setDirectionToTarget = function (target) {
  43025. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  43026. return this.direction;
  43027. };
  43028. /**
  43029. * Returns the light rotation in euler definition.
  43030. * @returns the x y z rotation in local space.
  43031. */
  43032. ShadowLight.prototype.getRotation = function () {
  43033. this.direction.normalize();
  43034. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  43035. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  43036. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  43037. };
  43038. /**
  43039. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  43040. * @returns true if a cube texture needs to be use
  43041. */
  43042. ShadowLight.prototype.needCube = function () {
  43043. return false;
  43044. };
  43045. /**
  43046. * Detects if the projection matrix requires to be recomputed this frame.
  43047. * @returns true if it requires to be recomputed otherwise, false.
  43048. */
  43049. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  43050. return this._needProjectionMatrixCompute;
  43051. };
  43052. /**
  43053. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  43054. */
  43055. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  43056. this._needProjectionMatrixCompute = true;
  43057. };
  43058. /**
  43059. * Get the world matrix of the sahdow lights.
  43060. * @ignore Internal Use Only
  43061. */
  43062. ShadowLight.prototype._getWorldMatrix = function () {
  43063. if (!this._worldMatrix) {
  43064. this._worldMatrix = BABYLON.Matrix.Identity();
  43065. }
  43066. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  43067. return this._worldMatrix;
  43068. };
  43069. /**
  43070. * Gets the minZ used for shadow according to both the scene and the light.
  43071. * @param activeCamera The camera we are returning the min for
  43072. * @returns the depth min z
  43073. */
  43074. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  43075. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  43076. };
  43077. /**
  43078. * Gets the maxZ used for shadow according to both the scene and the light.
  43079. * @param activeCamera The camera we are returning the max for
  43080. * @returns the depth max z
  43081. */
  43082. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  43083. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  43084. };
  43085. /**
  43086. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  43087. * @param matrix The materix to updated with the projection information
  43088. * @param viewMatrix The transform matrix of the light
  43089. * @param renderList The list of mesh to render in the map
  43090. * @returns The current light
  43091. */
  43092. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43093. if (this.customProjectionMatrixBuilder) {
  43094. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  43095. }
  43096. else {
  43097. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43098. }
  43099. return this;
  43100. };
  43101. __decorate([
  43102. BABYLON.serializeAsVector3()
  43103. ], ShadowLight.prototype, "position", void 0);
  43104. __decorate([
  43105. BABYLON.serializeAsVector3()
  43106. /**
  43107. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  43108. */
  43109. ], ShadowLight.prototype, "direction", null);
  43110. __decorate([
  43111. BABYLON.serialize()
  43112. ], ShadowLight.prototype, "shadowMinZ", null);
  43113. __decorate([
  43114. BABYLON.serialize()
  43115. ], ShadowLight.prototype, "shadowMaxZ", null);
  43116. return ShadowLight;
  43117. }(BABYLON.Light));
  43118. BABYLON.ShadowLight = ShadowLight;
  43119. })(BABYLON || (BABYLON = {}));
  43120. //# sourceMappingURL=babylon.shadowLight.js.map
  43121. var BABYLON;
  43122. (function (BABYLON) {
  43123. /**
  43124. * A point light is a light defined by an unique point in world space.
  43125. * The light is emitted in every direction from this point.
  43126. * A good example of a point light is a standard light bulb.
  43127. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43128. */
  43129. var PointLight = /** @class */ (function (_super) {
  43130. __extends(PointLight, _super);
  43131. /**
  43132. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  43133. * A PointLight emits the light in every direction.
  43134. * It can cast shadows.
  43135. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  43136. * ```javascript
  43137. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  43138. * ```
  43139. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43140. * @param name The light friendly name
  43141. * @param position The position of the point light in the scene
  43142. * @param scene The scene the lights belongs to
  43143. */
  43144. function PointLight(name, position, scene) {
  43145. var _this = _super.call(this, name, scene) || this;
  43146. _this._shadowAngle = Math.PI / 2;
  43147. _this.position = position;
  43148. return _this;
  43149. }
  43150. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  43151. /**
  43152. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43153. * This specifies what angle the shadow will use to be created.
  43154. *
  43155. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43156. */
  43157. get: function () {
  43158. return this._shadowAngle;
  43159. },
  43160. /**
  43161. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43162. * This specifies what angle the shadow will use to be created.
  43163. *
  43164. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43165. */
  43166. set: function (value) {
  43167. this._shadowAngle = value;
  43168. this.forceProjectionMatrixCompute();
  43169. },
  43170. enumerable: true,
  43171. configurable: true
  43172. });
  43173. Object.defineProperty(PointLight.prototype, "direction", {
  43174. /**
  43175. * Gets the direction if it has been set.
  43176. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43177. */
  43178. get: function () {
  43179. return this._direction;
  43180. },
  43181. /**
  43182. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43183. */
  43184. set: function (value) {
  43185. var previousNeedCube = this.needCube();
  43186. this._direction = value;
  43187. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  43188. this._shadowGenerator.recreateShadowMap();
  43189. }
  43190. },
  43191. enumerable: true,
  43192. configurable: true
  43193. });
  43194. /**
  43195. * Returns the string "PointLight"
  43196. * @returns the class name
  43197. */
  43198. PointLight.prototype.getClassName = function () {
  43199. return "PointLight";
  43200. };
  43201. /**
  43202. * Returns the integer 0.
  43203. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43204. */
  43205. PointLight.prototype.getTypeID = function () {
  43206. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  43207. };
  43208. /**
  43209. * Specifies wether or not the shadowmap should be a cube texture.
  43210. * @returns true if the shadowmap needs to be a cube texture.
  43211. */
  43212. PointLight.prototype.needCube = function () {
  43213. return !this.direction;
  43214. };
  43215. /**
  43216. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  43217. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43218. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43219. */
  43220. PointLight.prototype.getShadowDirection = function (faceIndex) {
  43221. if (this.direction) {
  43222. return _super.prototype.getShadowDirection.call(this, faceIndex);
  43223. }
  43224. else {
  43225. switch (faceIndex) {
  43226. case 0:
  43227. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  43228. case 1:
  43229. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  43230. case 2:
  43231. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  43232. case 3:
  43233. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  43234. case 4:
  43235. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  43236. case 5:
  43237. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  43238. }
  43239. }
  43240. return BABYLON.Vector3.Zero();
  43241. };
  43242. /**
  43243. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  43244. * - fov = PI / 2
  43245. * - aspect ratio : 1.0
  43246. * - z-near and far equal to the active camera minZ and maxZ.
  43247. * Returns the PointLight.
  43248. */
  43249. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43250. var activeCamera = this.getScene().activeCamera;
  43251. if (!activeCamera) {
  43252. return;
  43253. }
  43254. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43255. };
  43256. PointLight.prototype._buildUniformLayout = function () {
  43257. this._uniformBuffer.addUniform("vLightData", 4);
  43258. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43259. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43260. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43261. this._uniformBuffer.addUniform("depthValues", 2);
  43262. this._uniformBuffer.create();
  43263. };
  43264. /**
  43265. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  43266. * @param effect The effect to update
  43267. * @param lightIndex The index of the light in the effect to update
  43268. * @returns The point light
  43269. */
  43270. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  43271. if (this.computeTransformedInformation()) {
  43272. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  43273. return this;
  43274. }
  43275. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  43276. return this;
  43277. };
  43278. __decorate([
  43279. BABYLON.serialize()
  43280. ], PointLight.prototype, "shadowAngle", null);
  43281. return PointLight;
  43282. }(BABYLON.ShadowLight));
  43283. BABYLON.PointLight = PointLight;
  43284. })(BABYLON || (BABYLON = {}));
  43285. //# sourceMappingURL=babylon.pointLight.js.map
  43286. var BABYLON;
  43287. (function (BABYLON) {
  43288. /**
  43289. * A directional light is defined by a direction (what a surprise!).
  43290. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  43291. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  43292. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43293. */
  43294. var DirectionalLight = /** @class */ (function (_super) {
  43295. __extends(DirectionalLight, _super);
  43296. /**
  43297. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  43298. * The directional light is emitted from everywhere in the given direction.
  43299. * It can cast shawdows.
  43300. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43301. * @param name The friendly name of the light
  43302. * @param direction The direction of the light
  43303. * @param scene The scene the light belongs to
  43304. */
  43305. function DirectionalLight(name, direction, scene) {
  43306. var _this = _super.call(this, name, scene) || this;
  43307. _this._shadowFrustumSize = 0;
  43308. _this._shadowOrthoScale = 0.5;
  43309. /**
  43310. * Automatically compute the projection matrix to best fit (including all the casters)
  43311. * on each frame.
  43312. */
  43313. _this.autoUpdateExtends = true;
  43314. // Cache
  43315. _this._orthoLeft = Number.MAX_VALUE;
  43316. _this._orthoRight = Number.MIN_VALUE;
  43317. _this._orthoTop = Number.MIN_VALUE;
  43318. _this._orthoBottom = Number.MAX_VALUE;
  43319. _this.position = direction.scale(-1.0);
  43320. _this.direction = direction;
  43321. return _this;
  43322. }
  43323. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  43324. /**
  43325. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  43326. */
  43327. get: function () {
  43328. return this._shadowFrustumSize;
  43329. },
  43330. /**
  43331. * Specifies a fix frustum size for the shadow generation.
  43332. */
  43333. set: function (value) {
  43334. this._shadowFrustumSize = value;
  43335. this.forceProjectionMatrixCompute();
  43336. },
  43337. enumerable: true,
  43338. configurable: true
  43339. });
  43340. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  43341. /**
  43342. * Gets the shadow projection scale against the optimal computed one.
  43343. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43344. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43345. */
  43346. get: function () {
  43347. return this._shadowOrthoScale;
  43348. },
  43349. /**
  43350. * Sets the shadow projection scale against the optimal computed one.
  43351. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43352. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43353. */
  43354. set: function (value) {
  43355. this._shadowOrthoScale = value;
  43356. this.forceProjectionMatrixCompute();
  43357. },
  43358. enumerable: true,
  43359. configurable: true
  43360. });
  43361. /**
  43362. * Returns the string "DirectionalLight".
  43363. * @return The class name
  43364. */
  43365. DirectionalLight.prototype.getClassName = function () {
  43366. return "DirectionalLight";
  43367. };
  43368. /**
  43369. * Returns the integer 1.
  43370. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43371. */
  43372. DirectionalLight.prototype.getTypeID = function () {
  43373. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  43374. };
  43375. /**
  43376. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  43377. * Returns the DirectionalLight Shadow projection matrix.
  43378. */
  43379. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43380. if (this.shadowFrustumSize > 0) {
  43381. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43382. }
  43383. else {
  43384. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43385. }
  43386. };
  43387. /**
  43388. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43389. * Returns the DirectionalLight Shadow projection matrix.
  43390. */
  43391. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43392. var activeCamera = this.getScene().activeCamera;
  43393. if (!activeCamera) {
  43394. return;
  43395. }
  43396. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43397. };
  43398. /**
  43399. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43400. * Returns the DirectionalLight Shadow projection matrix.
  43401. */
  43402. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43403. var activeCamera = this.getScene().activeCamera;
  43404. if (!activeCamera) {
  43405. return;
  43406. }
  43407. // Check extends
  43408. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43409. var tempVector3 = BABYLON.Vector3.Zero();
  43410. this._orthoLeft = Number.MAX_VALUE;
  43411. this._orthoRight = Number.MIN_VALUE;
  43412. this._orthoTop = Number.MIN_VALUE;
  43413. this._orthoBottom = Number.MAX_VALUE;
  43414. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43415. var mesh = renderList[meshIndex];
  43416. if (!mesh) {
  43417. continue;
  43418. }
  43419. var boundingInfo = mesh.getBoundingInfo();
  43420. var boundingBox = boundingInfo.boundingBox;
  43421. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43422. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43423. if (tempVector3.x < this._orthoLeft)
  43424. this._orthoLeft = tempVector3.x;
  43425. if (tempVector3.y < this._orthoBottom)
  43426. this._orthoBottom = tempVector3.y;
  43427. if (tempVector3.x > this._orthoRight)
  43428. this._orthoRight = tempVector3.x;
  43429. if (tempVector3.y > this._orthoTop)
  43430. this._orthoTop = tempVector3.y;
  43431. }
  43432. }
  43433. }
  43434. var xOffset = this._orthoRight - this._orthoLeft;
  43435. var yOffset = this._orthoTop - this._orthoBottom;
  43436. 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);
  43437. };
  43438. DirectionalLight.prototype._buildUniformLayout = function () {
  43439. this._uniformBuffer.addUniform("vLightData", 4);
  43440. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43441. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43442. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43443. this._uniformBuffer.addUniform("depthValues", 2);
  43444. this._uniformBuffer.create();
  43445. };
  43446. /**
  43447. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43448. * @param effect The effect to update
  43449. * @param lightIndex The index of the light in the effect to update
  43450. * @returns The directional light
  43451. */
  43452. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43453. if (this.computeTransformedInformation()) {
  43454. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43455. return this;
  43456. }
  43457. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43458. return this;
  43459. };
  43460. /**
  43461. * Gets the minZ used for shadow according to both the scene and the light.
  43462. *
  43463. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43464. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43465. * @param activeCamera The camera we are returning the min for
  43466. * @returns the depth min z
  43467. */
  43468. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43469. return 1;
  43470. };
  43471. /**
  43472. * Gets the maxZ used for shadow according to both the scene and the light.
  43473. *
  43474. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43475. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43476. * @param activeCamera The camera we are returning the max for
  43477. * @returns the depth max z
  43478. */
  43479. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43480. return 1;
  43481. };
  43482. __decorate([
  43483. BABYLON.serialize()
  43484. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43485. __decorate([
  43486. BABYLON.serialize()
  43487. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43488. __decorate([
  43489. BABYLON.serialize()
  43490. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43491. return DirectionalLight;
  43492. }(BABYLON.ShadowLight));
  43493. BABYLON.DirectionalLight = DirectionalLight;
  43494. })(BABYLON || (BABYLON = {}));
  43495. //# sourceMappingURL=babylon.directionalLight.js.map
  43496. var BABYLON;
  43497. (function (BABYLON) {
  43498. /**
  43499. * A spot light is defined by a position, a direction, an angle, and an exponent.
  43500. * These values define a cone of light starting from the position, emitting toward the direction.
  43501. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  43502. * and the exponent defines the speed of the decay of the light with distance (reach).
  43503. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43504. */
  43505. var SpotLight = /** @class */ (function (_super) {
  43506. __extends(SpotLight, _super);
  43507. /**
  43508. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  43509. * It can cast shadows.
  43510. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43511. * @param name The light friendly name
  43512. * @param position The position of the spot light in the scene
  43513. * @param direction The direction of the light in the scene
  43514. * @param angle The cone angle of the light in Radians
  43515. * @param exponent The light decay speed with the distance from the emission spot
  43516. * @param scene The scene the lights belongs to
  43517. */
  43518. function SpotLight(name, position, direction, angle, exponent, scene) {
  43519. var _this = _super.call(this, name, scene) || this;
  43520. _this._textureProjectionMatrix = BABYLON.Matrix.Zero();
  43521. _this.position = position;
  43522. _this.direction = direction;
  43523. _this.angle = angle;
  43524. _this.exponent = exponent;
  43525. return _this;
  43526. }
  43527. Object.defineProperty(SpotLight.prototype, "angle", {
  43528. get: function () {
  43529. return this._angle;
  43530. },
  43531. /**
  43532. * Sets the cone angle of the spot light in Radians.
  43533. */
  43534. set: function (value) {
  43535. this._angle = value;
  43536. this.forceProjectionMatrixCompute();
  43537. },
  43538. enumerable: true,
  43539. configurable: true
  43540. });
  43541. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43542. get: function () {
  43543. return this._shadowAngleScale;
  43544. },
  43545. /**
  43546. * Allows scaling the angle of the light for shadow generation only.
  43547. */
  43548. set: function (value) {
  43549. this._shadowAngleScale = value;
  43550. this.forceProjectionMatrixCompute();
  43551. },
  43552. enumerable: true,
  43553. configurable: true
  43554. });
  43555. Object.defineProperty(SpotLight.prototype, "textureMatrix", {
  43556. get: function () {
  43557. return this._textureProjectionMatrix;
  43558. },
  43559. /**
  43560. * Allows setting the value of projection texture
  43561. */
  43562. set: function (value) {
  43563. this._textureProjectionMatrix = value;
  43564. },
  43565. enumerable: true,
  43566. configurable: true
  43567. });
  43568. Object.defineProperty(SpotLight.prototype, "light_near", {
  43569. get: function () {
  43570. return this._light_near;
  43571. },
  43572. /**
  43573. * Sets the near clip of the Spotlight for texture projection.
  43574. */
  43575. set: function (value) {
  43576. this._light_near = value;
  43577. this._computeTextureMatrix();
  43578. },
  43579. enumerable: true,
  43580. configurable: true
  43581. });
  43582. Object.defineProperty(SpotLight.prototype, "light_far", {
  43583. /**
  43584. * Gets the far clip of the Spotlight for texture projection.
  43585. */
  43586. get: function () {
  43587. return this._light_far;
  43588. },
  43589. /**
  43590. * Sets the far clip of the Spotlight for texture projection.
  43591. */
  43592. set: function (value) {
  43593. this._light_far = value;
  43594. },
  43595. enumerable: true,
  43596. configurable: true
  43597. });
  43598. ;
  43599. Object.defineProperty(SpotLight.prototype, "projectedLightTexture", {
  43600. /**
  43601. * Gets the projection texture of the light.
  43602. */
  43603. get: function () {
  43604. return this._projectedLightTexture;
  43605. },
  43606. /**
  43607. * Sets the projection texture of the light.
  43608. */
  43609. set: function (value) {
  43610. this._projectedLightTexture = value;
  43611. this._light_far = 1000.0;
  43612. this._light_near = 1e-6;
  43613. this._computeTextureMatrix();
  43614. },
  43615. enumerable: true,
  43616. configurable: true
  43617. });
  43618. /**
  43619. * Returns the string "SpotLight".
  43620. * @returns the class name
  43621. */
  43622. SpotLight.prototype.getClassName = function () {
  43623. return "SpotLight";
  43624. };
  43625. /**
  43626. * Returns the integer 2.
  43627. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43628. */
  43629. SpotLight.prototype.getTypeID = function () {
  43630. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43631. };
  43632. /**
  43633. * 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.
  43634. * Returns the SpotLight.
  43635. */
  43636. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43637. var activeCamera = this.getScene().activeCamera;
  43638. if (!activeCamera) {
  43639. return;
  43640. }
  43641. this._shadowAngleScale = this._shadowAngleScale || 1;
  43642. var angle = this._shadowAngleScale * this._angle;
  43643. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43644. };
  43645. /**
  43646. * Main function for light texture projection matrix computing.
  43647. */
  43648. SpotLight.prototype._computeTextureMatrix = function () {
  43649. var viewLightMatrix = BABYLON.Matrix.Zero();
  43650. BABYLON.Matrix.LookAtLHToRef(this.position, this.position.add(this.direction), BABYLON.Vector3.Up(), viewLightMatrix);
  43651. var light_far = this.light_far;
  43652. var light_near = this.light_near;
  43653. var P = light_far / (light_far - light_near);
  43654. var Q = -P * light_near;
  43655. var S = 1.0 / Math.tan(this._angle / 2.0);
  43656. var A = 1.0;
  43657. var projectionLightMatrix = BABYLON.Matrix.Zero();
  43658. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, projectionLightMatrix);
  43659. var scaleMatrix = BABYLON.Matrix.Zero();
  43660. BABYLON.Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, scaleMatrix);
  43661. this._textureProjectionMatrix.copyFrom(viewLightMatrix);
  43662. this._textureProjectionMatrix.multiplyToRef(projectionLightMatrix, this._textureProjectionMatrix);
  43663. this._textureProjectionMatrix.multiplyToRef(scaleMatrix, this._textureProjectionMatrix);
  43664. };
  43665. SpotLight.prototype._buildUniformLayout = function () {
  43666. this._uniformBuffer.addUniform("vLightData", 4);
  43667. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43668. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43669. this._uniformBuffer.addUniform("vLightDirection", 3);
  43670. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43671. this._uniformBuffer.addUniform("depthValues", 2);
  43672. this._uniformBuffer.create();
  43673. };
  43674. /**
  43675. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43676. * @param effect The effect to update
  43677. * @param lightIndex The index of the light in the effect to update
  43678. * @returns The spot light
  43679. */
  43680. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43681. var normalizeDirection;
  43682. if (this.computeTransformedInformation()) {
  43683. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43684. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43685. }
  43686. else {
  43687. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43688. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43689. }
  43690. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43691. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._textureProjectionMatrix);
  43692. if (this.projectedLightTexture) {
  43693. effect.setTexture("projectionLightSampler" + lightIndex, this.projectedLightTexture);
  43694. }
  43695. return this;
  43696. };
  43697. /**
  43698. * Disposes the light and the associated resources.
  43699. */
  43700. SpotLight.prototype.dispose = function () {
  43701. _super.prototype.dispose.call(this);
  43702. if (this._projectedLightTexture) {
  43703. this._projectedLightTexture.dispose();
  43704. }
  43705. };
  43706. __decorate([
  43707. BABYLON.serialize()
  43708. /**
  43709. * Gets the cone angle of the spot light in Radians.
  43710. */
  43711. ], SpotLight.prototype, "angle", null);
  43712. __decorate([
  43713. BABYLON.serialize()
  43714. /**
  43715. * Allows scaling the angle of the light for shadow generation only.
  43716. */
  43717. ], SpotLight.prototype, "shadowAngleScale", null);
  43718. __decorate([
  43719. BABYLON.serialize()
  43720. ], SpotLight.prototype, "exponent", void 0);
  43721. __decorate([
  43722. BABYLON.serialize()
  43723. /**
  43724. * Allows reading the projecton texture
  43725. */
  43726. ], SpotLight.prototype, "textureMatrix", null);
  43727. __decorate([
  43728. BABYLON.serialize()
  43729. /**
  43730. * Gets the near clip of the Spotlight for texture projection.
  43731. */
  43732. ], SpotLight.prototype, "light_near", null);
  43733. __decorate([
  43734. BABYLON.serialize()
  43735. ], SpotLight.prototype, "light_far", null);
  43736. __decorate([
  43737. BABYLON.serializeAsTexture("projectedLightTexture")
  43738. ], SpotLight.prototype, "_projectedLightTexture", void 0);
  43739. return SpotLight;
  43740. }(BABYLON.ShadowLight));
  43741. BABYLON.SpotLight = SpotLight;
  43742. })(BABYLON || (BABYLON = {}));
  43743. //# sourceMappingURL=babylon.spotLight.js.map
  43744. var BABYLON;
  43745. (function (BABYLON) {
  43746. var AnimationRange = /** @class */ (function () {
  43747. function AnimationRange(name, from, to) {
  43748. this.name = name;
  43749. this.from = from;
  43750. this.to = to;
  43751. }
  43752. AnimationRange.prototype.clone = function () {
  43753. return new AnimationRange(this.name, this.from, this.to);
  43754. };
  43755. return AnimationRange;
  43756. }());
  43757. BABYLON.AnimationRange = AnimationRange;
  43758. /**
  43759. * Composed of a frame, and an action function
  43760. */
  43761. var AnimationEvent = /** @class */ (function () {
  43762. function AnimationEvent(frame, action, onlyOnce) {
  43763. this.frame = frame;
  43764. this.action = action;
  43765. this.onlyOnce = onlyOnce;
  43766. this.isDone = false;
  43767. }
  43768. return AnimationEvent;
  43769. }());
  43770. BABYLON.AnimationEvent = AnimationEvent;
  43771. var PathCursor = /** @class */ (function () {
  43772. function PathCursor(path) {
  43773. this.path = path;
  43774. this._onchange = new Array();
  43775. this.value = 0;
  43776. this.animations = new Array();
  43777. }
  43778. PathCursor.prototype.getPoint = function () {
  43779. var point = this.path.getPointAtLengthPosition(this.value);
  43780. return new BABYLON.Vector3(point.x, 0, point.y);
  43781. };
  43782. PathCursor.prototype.moveAhead = function (step) {
  43783. if (step === void 0) { step = 0.002; }
  43784. this.move(step);
  43785. return this;
  43786. };
  43787. PathCursor.prototype.moveBack = function (step) {
  43788. if (step === void 0) { step = 0.002; }
  43789. this.move(-step);
  43790. return this;
  43791. };
  43792. PathCursor.prototype.move = function (step) {
  43793. if (Math.abs(step) > 1) {
  43794. throw "step size should be less than 1.";
  43795. }
  43796. this.value += step;
  43797. this.ensureLimits();
  43798. this.raiseOnChange();
  43799. return this;
  43800. };
  43801. PathCursor.prototype.ensureLimits = function () {
  43802. while (this.value > 1) {
  43803. this.value -= 1;
  43804. }
  43805. while (this.value < 0) {
  43806. this.value += 1;
  43807. }
  43808. return this;
  43809. };
  43810. // used by animation engine
  43811. PathCursor.prototype.raiseOnChange = function () {
  43812. var _this = this;
  43813. this._onchange.forEach(function (f) { return f(_this); });
  43814. return this;
  43815. };
  43816. PathCursor.prototype.onchange = function (f) {
  43817. this._onchange.push(f);
  43818. return this;
  43819. };
  43820. return PathCursor;
  43821. }());
  43822. BABYLON.PathCursor = PathCursor;
  43823. var AnimationKeyInterpolation;
  43824. (function (AnimationKeyInterpolation) {
  43825. /**
  43826. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  43827. */
  43828. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43829. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43830. var Animation = /** @class */ (function () {
  43831. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43832. this.name = name;
  43833. this.targetProperty = targetProperty;
  43834. this.framePerSecond = framePerSecond;
  43835. this.dataType = dataType;
  43836. this.loopMode = loopMode;
  43837. this.enableBlending = enableBlending;
  43838. this._runtimeAnimations = new Array();
  43839. // The set of event that will be linked to this animation
  43840. this._events = new Array();
  43841. this.blendingSpeed = 0.01;
  43842. this._ranges = {};
  43843. this.targetPropertyPath = targetProperty.split(".");
  43844. this.dataType = dataType;
  43845. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43846. }
  43847. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43848. var dataType = undefined;
  43849. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43850. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43851. }
  43852. else if (from instanceof BABYLON.Quaternion) {
  43853. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43854. }
  43855. else if (from instanceof BABYLON.Vector3) {
  43856. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43857. }
  43858. else if (from instanceof BABYLON.Vector2) {
  43859. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43860. }
  43861. else if (from instanceof BABYLON.Color3) {
  43862. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43863. }
  43864. else if (from instanceof BABYLON.Size) {
  43865. dataType = Animation.ANIMATIONTYPE_SIZE;
  43866. }
  43867. if (dataType == undefined) {
  43868. return null;
  43869. }
  43870. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43871. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43872. animation.setKeys(keys);
  43873. if (easingFunction !== undefined) {
  43874. animation.setEasingFunction(easingFunction);
  43875. }
  43876. return animation;
  43877. };
  43878. /**
  43879. * Sets up an animation.
  43880. * @param property the property to animate
  43881. * @param animationType the animation type to apply
  43882. * @param easingFunction the easing function used in the animation
  43883. * @returns The created animation
  43884. */
  43885. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43886. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43887. animation.setEasingFunction(easingFunction);
  43888. return animation;
  43889. };
  43890. /**
  43891. * Create and start an animation on a node
  43892. * @param {string} name defines the name of the global animation that will be run on all nodes
  43893. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43894. * @param {string} targetProperty defines property to animate
  43895. * @param {number} framePerSecond defines the number of frame per second yo use
  43896. * @param {number} totalFrame defines the number of frames in total
  43897. * @param {any} from defines the initial value
  43898. * @param {any} to defines the final value
  43899. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43900. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43901. * @param onAnimationEnd defines the callback to call when animation end
  43902. * @returns the animatable created for this animation
  43903. */
  43904. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43905. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43906. if (!animation) {
  43907. return null;
  43908. }
  43909. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43910. };
  43911. /**
  43912. * Create and start an animation on a node and its descendants
  43913. * @param {string} name defines the name of the global animation that will be run on all nodes
  43914. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43915. * @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.
  43916. * @param {string} targetProperty defines property to animate
  43917. * @param {number} framePerSecond defines the number of frame per second yo use
  43918. * @param {number} totalFrame defines the number of frames in total
  43919. * @param {any} from defines the initial value
  43920. * @param {any} to defines the final value
  43921. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43922. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43923. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43924. * @returns the list of animatables created for all nodes
  43925. * @example https://www.babylonjs-playground.com/#MH0VLI
  43926. */
  43927. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43928. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43929. if (!animation) {
  43930. return null;
  43931. }
  43932. var scene = node.getScene();
  43933. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43934. };
  43935. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43936. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43937. if (!animation) {
  43938. return null;
  43939. }
  43940. node.animations.push(animation);
  43941. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43942. };
  43943. /**
  43944. * Transition property of the Camera to the target Value.
  43945. * @param property The property to transition
  43946. * @param targetValue The target Value of the property
  43947. * @param host The object where the property to animate belongs
  43948. * @param scene Scene used to run the animation
  43949. * @param frameRate Framerate (in frame/s) to use
  43950. * @param transition The transition type we want to use
  43951. * @param duration The duration of the animation, in milliseconds
  43952. * @param onAnimationEnd Call back trigger at the end of the animation.
  43953. */
  43954. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43955. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43956. if (duration <= 0) {
  43957. host[property] = targetValue;
  43958. if (onAnimationEnd) {
  43959. onAnimationEnd();
  43960. }
  43961. return null;
  43962. }
  43963. var endFrame = frameRate * (duration / 1000);
  43964. transition.setKeys([{
  43965. frame: 0,
  43966. value: host[property].clone ? host[property].clone() : host[property]
  43967. },
  43968. {
  43969. frame: endFrame,
  43970. value: targetValue
  43971. }]);
  43972. if (!host.animations) {
  43973. host.animations = [];
  43974. }
  43975. host.animations.push(transition);
  43976. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43977. animation.onAnimationEnd = onAnimationEnd;
  43978. return animation;
  43979. };
  43980. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43981. /**
  43982. * Return the array of runtime animations currently using this animation
  43983. */
  43984. get: function () {
  43985. return this._runtimeAnimations;
  43986. },
  43987. enumerable: true,
  43988. configurable: true
  43989. });
  43990. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43991. get: function () {
  43992. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43993. var runtimeAnimation = _a[_i];
  43994. if (!runtimeAnimation.isStopped) {
  43995. return true;
  43996. }
  43997. }
  43998. return false;
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. // Methods
  44004. /**
  44005. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  44006. */
  44007. Animation.prototype.toString = function (fullDetails) {
  44008. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  44009. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  44010. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  44011. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  44012. if (fullDetails) {
  44013. ret += ", Ranges: {";
  44014. var first = true;
  44015. for (var name in this._ranges) {
  44016. if (first) {
  44017. ret += ", ";
  44018. first = false;
  44019. }
  44020. ret += name;
  44021. }
  44022. ret += "}";
  44023. }
  44024. return ret;
  44025. };
  44026. /**
  44027. * Add an event to this animation.
  44028. */
  44029. Animation.prototype.addEvent = function (event) {
  44030. this._events.push(event);
  44031. };
  44032. /**
  44033. * Remove all events found at the given frame
  44034. * @param frame
  44035. */
  44036. Animation.prototype.removeEvents = function (frame) {
  44037. for (var index = 0; index < this._events.length; index++) {
  44038. if (this._events[index].frame === frame) {
  44039. this._events.splice(index, 1);
  44040. index--;
  44041. }
  44042. }
  44043. };
  44044. Animation.prototype.getEvents = function () {
  44045. return this._events;
  44046. };
  44047. Animation.prototype.createRange = function (name, from, to) {
  44048. // check name not already in use; could happen for bones after serialized
  44049. if (!this._ranges[name]) {
  44050. this._ranges[name] = new AnimationRange(name, from, to);
  44051. }
  44052. };
  44053. Animation.prototype.deleteRange = function (name, deleteFrames) {
  44054. if (deleteFrames === void 0) { deleteFrames = true; }
  44055. var range = this._ranges[name];
  44056. if (!range) {
  44057. return;
  44058. }
  44059. if (deleteFrames) {
  44060. var from = range.from;
  44061. var to = range.to;
  44062. // this loop MUST go high to low for multiple splices to work
  44063. for (var key = this._keys.length - 1; key >= 0; key--) {
  44064. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  44065. this._keys.splice(key, 1);
  44066. }
  44067. }
  44068. }
  44069. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  44070. };
  44071. Animation.prototype.getRange = function (name) {
  44072. return this._ranges[name];
  44073. };
  44074. Animation.prototype.getKeys = function () {
  44075. return this._keys;
  44076. };
  44077. Animation.prototype.getHighestFrame = function () {
  44078. var ret = 0;
  44079. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  44080. if (ret < this._keys[key].frame) {
  44081. ret = this._keys[key].frame;
  44082. }
  44083. }
  44084. return ret;
  44085. };
  44086. Animation.prototype.getEasingFunction = function () {
  44087. return this._easingFunction;
  44088. };
  44089. Animation.prototype.setEasingFunction = function (easingFunction) {
  44090. this._easingFunction = easingFunction;
  44091. };
  44092. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  44093. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  44094. };
  44095. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44096. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44097. };
  44098. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  44099. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  44100. };
  44101. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44102. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  44103. };
  44104. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  44105. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  44106. };
  44107. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44108. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44109. };
  44110. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  44111. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  44112. };
  44113. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44114. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44115. };
  44116. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  44117. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  44118. };
  44119. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  44120. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  44121. };
  44122. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  44123. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  44124. };
  44125. Animation.prototype.clone = function () {
  44126. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  44127. clone.enableBlending = this.enableBlending;
  44128. clone.blendingSpeed = this.blendingSpeed;
  44129. if (this._keys) {
  44130. clone.setKeys(this._keys);
  44131. }
  44132. if (this._ranges) {
  44133. clone._ranges = {};
  44134. for (var name in this._ranges) {
  44135. var range = this._ranges[name];
  44136. if (!range) {
  44137. continue;
  44138. }
  44139. clone._ranges[name] = range.clone();
  44140. }
  44141. }
  44142. return clone;
  44143. };
  44144. Animation.prototype.setKeys = function (values) {
  44145. this._keys = values.slice(0);
  44146. };
  44147. Animation.prototype.serialize = function () {
  44148. var serializationObject = {};
  44149. serializationObject.name = this.name;
  44150. serializationObject.property = this.targetProperty;
  44151. serializationObject.framePerSecond = this.framePerSecond;
  44152. serializationObject.dataType = this.dataType;
  44153. serializationObject.loopBehavior = this.loopMode;
  44154. serializationObject.enableBlending = this.enableBlending;
  44155. serializationObject.blendingSpeed = this.blendingSpeed;
  44156. var dataType = this.dataType;
  44157. serializationObject.keys = [];
  44158. var keys = this.getKeys();
  44159. for (var index = 0; index < keys.length; index++) {
  44160. var animationKey = keys[index];
  44161. var key = {};
  44162. key.frame = animationKey.frame;
  44163. switch (dataType) {
  44164. case Animation.ANIMATIONTYPE_FLOAT:
  44165. key.values = [animationKey.value];
  44166. break;
  44167. case Animation.ANIMATIONTYPE_QUATERNION:
  44168. case Animation.ANIMATIONTYPE_MATRIX:
  44169. case Animation.ANIMATIONTYPE_VECTOR3:
  44170. case Animation.ANIMATIONTYPE_COLOR3:
  44171. key.values = animationKey.value.asArray();
  44172. break;
  44173. }
  44174. serializationObject.keys.push(key);
  44175. }
  44176. serializationObject.ranges = [];
  44177. for (var name in this._ranges) {
  44178. var source = this._ranges[name];
  44179. if (!source) {
  44180. continue;
  44181. }
  44182. var range = {};
  44183. range.name = name;
  44184. range.from = source.from;
  44185. range.to = source.to;
  44186. serializationObject.ranges.push(range);
  44187. }
  44188. return serializationObject;
  44189. };
  44190. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  44191. get: function () {
  44192. return Animation._ANIMATIONTYPE_FLOAT;
  44193. },
  44194. enumerable: true,
  44195. configurable: true
  44196. });
  44197. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  44198. get: function () {
  44199. return Animation._ANIMATIONTYPE_VECTOR3;
  44200. },
  44201. enumerable: true,
  44202. configurable: true
  44203. });
  44204. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  44205. get: function () {
  44206. return Animation._ANIMATIONTYPE_VECTOR2;
  44207. },
  44208. enumerable: true,
  44209. configurable: true
  44210. });
  44211. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  44212. get: function () {
  44213. return Animation._ANIMATIONTYPE_SIZE;
  44214. },
  44215. enumerable: true,
  44216. configurable: true
  44217. });
  44218. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  44219. get: function () {
  44220. return Animation._ANIMATIONTYPE_QUATERNION;
  44221. },
  44222. enumerable: true,
  44223. configurable: true
  44224. });
  44225. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  44226. get: function () {
  44227. return Animation._ANIMATIONTYPE_MATRIX;
  44228. },
  44229. enumerable: true,
  44230. configurable: true
  44231. });
  44232. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  44233. get: function () {
  44234. return Animation._ANIMATIONTYPE_COLOR3;
  44235. },
  44236. enumerable: true,
  44237. configurable: true
  44238. });
  44239. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  44240. get: function () {
  44241. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  44242. },
  44243. enumerable: true,
  44244. configurable: true
  44245. });
  44246. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  44247. get: function () {
  44248. return Animation._ANIMATIONLOOPMODE_CYCLE;
  44249. },
  44250. enumerable: true,
  44251. configurable: true
  44252. });
  44253. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  44254. get: function () {
  44255. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  44256. },
  44257. enumerable: true,
  44258. configurable: true
  44259. });
  44260. Animation.Parse = function (parsedAnimation) {
  44261. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  44262. var dataType = parsedAnimation.dataType;
  44263. var keys = [];
  44264. var data;
  44265. var index;
  44266. if (parsedAnimation.enableBlending) {
  44267. animation.enableBlending = parsedAnimation.enableBlending;
  44268. }
  44269. if (parsedAnimation.blendingSpeed) {
  44270. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  44271. }
  44272. for (index = 0; index < parsedAnimation.keys.length; index++) {
  44273. var key = parsedAnimation.keys[index];
  44274. var inTangent;
  44275. var outTangent;
  44276. switch (dataType) {
  44277. case Animation.ANIMATIONTYPE_FLOAT:
  44278. data = key.values[0];
  44279. if (key.values.length >= 1) {
  44280. inTangent = key.values[1];
  44281. }
  44282. if (key.values.length >= 2) {
  44283. outTangent = key.values[2];
  44284. }
  44285. break;
  44286. case Animation.ANIMATIONTYPE_QUATERNION:
  44287. data = BABYLON.Quaternion.FromArray(key.values);
  44288. if (key.values.length >= 8) {
  44289. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  44290. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  44291. inTangent = _inTangent;
  44292. }
  44293. }
  44294. if (key.values.length >= 12) {
  44295. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  44296. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  44297. outTangent = _outTangent;
  44298. }
  44299. }
  44300. break;
  44301. case Animation.ANIMATIONTYPE_MATRIX:
  44302. data = BABYLON.Matrix.FromArray(key.values);
  44303. break;
  44304. case Animation.ANIMATIONTYPE_COLOR3:
  44305. data = BABYLON.Color3.FromArray(key.values);
  44306. break;
  44307. case Animation.ANIMATIONTYPE_VECTOR3:
  44308. default:
  44309. data = BABYLON.Vector3.FromArray(key.values);
  44310. break;
  44311. }
  44312. var keyData = {};
  44313. keyData.frame = key.frame;
  44314. keyData.value = data;
  44315. if (inTangent != undefined) {
  44316. keyData.inTangent = inTangent;
  44317. }
  44318. if (outTangent != undefined) {
  44319. keyData.outTangent = outTangent;
  44320. }
  44321. keys.push(keyData);
  44322. }
  44323. animation.setKeys(keys);
  44324. if (parsedAnimation.ranges) {
  44325. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  44326. data = parsedAnimation.ranges[index];
  44327. animation.createRange(data.name, data.from, data.to);
  44328. }
  44329. }
  44330. return animation;
  44331. };
  44332. Animation.AppendSerializedAnimations = function (source, destination) {
  44333. if (source.animations) {
  44334. destination.animations = [];
  44335. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  44336. var animation = source.animations[animationIndex];
  44337. destination.animations.push(animation.serialize());
  44338. }
  44339. }
  44340. };
  44341. Animation.AllowMatricesInterpolation = false;
  44342. // Statics
  44343. Animation._ANIMATIONTYPE_FLOAT = 0;
  44344. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  44345. Animation._ANIMATIONTYPE_QUATERNION = 2;
  44346. Animation._ANIMATIONTYPE_MATRIX = 3;
  44347. Animation._ANIMATIONTYPE_COLOR3 = 4;
  44348. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  44349. Animation._ANIMATIONTYPE_SIZE = 6;
  44350. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  44351. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  44352. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  44353. return Animation;
  44354. }());
  44355. BABYLON.Animation = Animation;
  44356. })(BABYLON || (BABYLON = {}));
  44357. //# sourceMappingURL=babylon.animation.js.map
  44358. var BABYLON;
  44359. (function (BABYLON) {
  44360. /**
  44361. * This class defines the direct association between an animation and a target
  44362. */
  44363. var TargetedAnimation = /** @class */ (function () {
  44364. function TargetedAnimation() {
  44365. }
  44366. return TargetedAnimation;
  44367. }());
  44368. BABYLON.TargetedAnimation = TargetedAnimation;
  44369. /**
  44370. * Use this class to create coordinated animations on multiple targets
  44371. */
  44372. var AnimationGroup = /** @class */ (function () {
  44373. function AnimationGroup(name, scene) {
  44374. if (scene === void 0) { scene = null; }
  44375. this.name = name;
  44376. this._targetedAnimations = new Array();
  44377. this._animatables = new Array();
  44378. this._from = Number.MAX_VALUE;
  44379. this._to = -Number.MAX_VALUE;
  44380. this._speedRatio = 1;
  44381. this.onAnimationEndObservable = new BABYLON.Observable();
  44382. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44383. this._scene.animationGroups.push(this);
  44384. }
  44385. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  44386. /**
  44387. * Define if the animations are started
  44388. */
  44389. get: function () {
  44390. return this._isStarted;
  44391. },
  44392. enumerable: true,
  44393. configurable: true
  44394. });
  44395. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  44396. /**
  44397. * Gets or sets the speed ratio to use for all animations
  44398. */
  44399. get: function () {
  44400. return this._speedRatio;
  44401. },
  44402. /**
  44403. * Gets or sets the speed ratio to use for all animations
  44404. */
  44405. set: function (value) {
  44406. if (this._speedRatio === value) {
  44407. return;
  44408. }
  44409. this._speedRatio = value;
  44410. for (var index = 0; index < this._animatables.length; index++) {
  44411. var animatable = this._animatables[index];
  44412. animatable.speedRatio = this._speedRatio;
  44413. }
  44414. },
  44415. enumerable: true,
  44416. configurable: true
  44417. });
  44418. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  44419. /**
  44420. * Gets the targeted animations for this animation group
  44421. */
  44422. get: function () {
  44423. return this._targetedAnimations;
  44424. },
  44425. enumerable: true,
  44426. configurable: true
  44427. });
  44428. /**
  44429. * Add an animation (with its target) in the group
  44430. * @param animation defines the animation we want to add
  44431. * @param target defines the target of the animation
  44432. * @returns the {BABYLON.TargetedAnimation} object
  44433. */
  44434. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  44435. var targetedAnimation = {
  44436. animation: animation,
  44437. target: target
  44438. };
  44439. var keys = animation.getKeys();
  44440. if (this._from > keys[0].frame) {
  44441. this._from = keys[0].frame;
  44442. }
  44443. if (this._to < keys[keys.length - 1].frame) {
  44444. this._to = keys[keys.length - 1].frame;
  44445. }
  44446. this._targetedAnimations.push(targetedAnimation);
  44447. return targetedAnimation;
  44448. };
  44449. /**
  44450. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  44451. * It can add constant keys at begin or end
  44452. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  44453. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  44454. */
  44455. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  44456. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  44457. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  44458. beginFrame = Math.max(beginFrame, this._from);
  44459. endFrame = Math.min(endFrame, this._to);
  44460. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44461. var targetedAnimation = this._targetedAnimations[index];
  44462. var keys = targetedAnimation.animation.getKeys();
  44463. var startKey = keys[0];
  44464. var endKey = keys[keys.length - 1];
  44465. if (startKey.frame > beginFrame) {
  44466. var newKey = {
  44467. frame: beginFrame,
  44468. value: startKey.value,
  44469. inTangent: startKey.inTangent,
  44470. outTangent: startKey.outTangent,
  44471. interpolation: startKey.interpolation
  44472. };
  44473. keys.splice(0, 0, newKey);
  44474. }
  44475. if (endKey.frame < endFrame) {
  44476. var newKey = {
  44477. frame: endFrame,
  44478. value: endKey.value,
  44479. inTangent: endKey.outTangent,
  44480. outTangent: endKey.outTangent,
  44481. interpolation: endKey.interpolation
  44482. };
  44483. keys.push(newKey);
  44484. }
  44485. }
  44486. return this;
  44487. };
  44488. /**
  44489. * Start all animations on given targets
  44490. * @param loop defines if animations must loop
  44491. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  44492. */
  44493. AnimationGroup.prototype.start = function (loop, speedRatio) {
  44494. var _this = this;
  44495. if (loop === void 0) { loop = false; }
  44496. if (speedRatio === void 0) { speedRatio = 1; }
  44497. if (this._isStarted || this._targetedAnimations.length === 0) {
  44498. return this;
  44499. }
  44500. var _loop_1 = function () {
  44501. var targetedAnimation = this_1._targetedAnimations[index];
  44502. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  44503. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  44504. }));
  44505. };
  44506. var this_1 = this;
  44507. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44508. _loop_1();
  44509. }
  44510. this._speedRatio = speedRatio;
  44511. this._isStarted = true;
  44512. return this;
  44513. };
  44514. /**
  44515. * Pause all animations
  44516. */
  44517. AnimationGroup.prototype.pause = function () {
  44518. if (!this._isStarted) {
  44519. return this;
  44520. }
  44521. for (var index = 0; index < this._animatables.length; index++) {
  44522. var animatable = this._animatables[index];
  44523. animatable.pause();
  44524. }
  44525. return this;
  44526. };
  44527. /**
  44528. * Play all animations to initial state
  44529. * This function will start() the animations if they were not started or will restart() them if they were paused
  44530. * @param loop defines if animations must loop
  44531. */
  44532. AnimationGroup.prototype.play = function (loop) {
  44533. if (this.isStarted) {
  44534. if (loop !== undefined) {
  44535. for (var index = 0; index < this._animatables.length; index++) {
  44536. var animatable = this._animatables[index];
  44537. animatable.loopAnimation = loop;
  44538. }
  44539. }
  44540. this.restart();
  44541. }
  44542. else {
  44543. this.start(loop, this._speedRatio);
  44544. }
  44545. return this;
  44546. };
  44547. /**
  44548. * Reset all animations to initial state
  44549. */
  44550. AnimationGroup.prototype.reset = function () {
  44551. if (!this._isStarted) {
  44552. return this;
  44553. }
  44554. for (var index = 0; index < this._animatables.length; index++) {
  44555. var animatable = this._animatables[index];
  44556. animatable.reset();
  44557. }
  44558. return this;
  44559. };
  44560. /**
  44561. * Restart animations from key 0
  44562. */
  44563. AnimationGroup.prototype.restart = function () {
  44564. if (!this._isStarted) {
  44565. return this;
  44566. }
  44567. for (var index = 0; index < this._animatables.length; index++) {
  44568. var animatable = this._animatables[index];
  44569. animatable.restart();
  44570. }
  44571. return this;
  44572. };
  44573. /**
  44574. * Stop all animations
  44575. */
  44576. AnimationGroup.prototype.stop = function () {
  44577. if (!this._isStarted) {
  44578. return this;
  44579. }
  44580. for (var index = 0; index < this._animatables.length; index++) {
  44581. var animatable = this._animatables[index];
  44582. animatable.stop();
  44583. }
  44584. this._isStarted = false;
  44585. return this;
  44586. };
  44587. /**
  44588. * Dispose all associated resources
  44589. */
  44590. AnimationGroup.prototype.dispose = function () {
  44591. this._targetedAnimations = [];
  44592. this._animatables = [];
  44593. var index = this._scene.animationGroups.indexOf(this);
  44594. if (index > -1) {
  44595. this._scene.animationGroups.splice(index, 1);
  44596. }
  44597. };
  44598. return AnimationGroup;
  44599. }());
  44600. BABYLON.AnimationGroup = AnimationGroup;
  44601. })(BABYLON || (BABYLON = {}));
  44602. //# sourceMappingURL=babylon.animationGroup.js.map
  44603. var BABYLON;
  44604. (function (BABYLON) {
  44605. var RuntimeAnimation = /** @class */ (function () {
  44606. function RuntimeAnimation(target, animation) {
  44607. this._offsetsCache = {};
  44608. this._highLimitsCache = {};
  44609. this._stopped = false;
  44610. this._blendingFactor = 0;
  44611. this._ratioOffset = 0;
  44612. this._animation = animation;
  44613. this._target = target;
  44614. animation._runtimeAnimations.push(this);
  44615. }
  44616. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44617. get: function () {
  44618. return this._animation;
  44619. },
  44620. enumerable: true,
  44621. configurable: true
  44622. });
  44623. RuntimeAnimation.prototype.reset = function () {
  44624. this._offsetsCache = {};
  44625. this._highLimitsCache = {};
  44626. this.currentFrame = 0;
  44627. this._blendingFactor = 0;
  44628. this._originalBlendValue = null;
  44629. };
  44630. RuntimeAnimation.prototype.isStopped = function () {
  44631. return this._stopped;
  44632. };
  44633. RuntimeAnimation.prototype.dispose = function () {
  44634. var index = this._animation.runtimeAnimations.indexOf(this);
  44635. if (index > -1) {
  44636. this._animation.runtimeAnimations.splice(index, 1);
  44637. }
  44638. };
  44639. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44640. if (typeof value === "function") {
  44641. return value();
  44642. }
  44643. return value;
  44644. };
  44645. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44646. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44647. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44648. }
  44649. this.currentFrame = currentFrame;
  44650. var keys = this._animation.getKeys();
  44651. // Try to get a hash to find the right key
  44652. 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));
  44653. if (keys[startKeyIndex].frame >= currentFrame) {
  44654. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44655. startKeyIndex--;
  44656. }
  44657. }
  44658. for (var key = startKeyIndex; key < keys.length; key++) {
  44659. var endKey = keys[key + 1];
  44660. if (endKey.frame >= currentFrame) {
  44661. var startKey = keys[key];
  44662. var startValue = this._getKeyValue(startKey.value);
  44663. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44664. return startValue;
  44665. }
  44666. var endValue = this._getKeyValue(endKey.value);
  44667. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44668. var frameDelta = endKey.frame - startKey.frame;
  44669. // gradient : percent of currentFrame between the frame inf and the frame sup
  44670. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44671. // check for easingFunction and correction of gradient
  44672. var easingFunction = this._animation.getEasingFunction();
  44673. if (easingFunction != null) {
  44674. gradient = easingFunction.ease(gradient);
  44675. }
  44676. switch (this._animation.dataType) {
  44677. // Float
  44678. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44679. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44680. switch (loopMode) {
  44681. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44682. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44683. return floatValue;
  44684. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44685. return offsetValue * repeatCount + floatValue;
  44686. }
  44687. break;
  44688. // Quaternion
  44689. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44690. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44691. switch (loopMode) {
  44692. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44693. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44694. return quatValue;
  44695. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44696. return quatValue.add(offsetValue.scale(repeatCount));
  44697. }
  44698. return quatValue;
  44699. // Vector3
  44700. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44701. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44702. switch (loopMode) {
  44703. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44704. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44705. return vec3Value;
  44706. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44707. return vec3Value.add(offsetValue.scale(repeatCount));
  44708. }
  44709. // Vector2
  44710. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44711. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44712. switch (loopMode) {
  44713. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44714. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44715. return vec2Value;
  44716. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44717. return vec2Value.add(offsetValue.scale(repeatCount));
  44718. }
  44719. // Size
  44720. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44721. switch (loopMode) {
  44722. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44723. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44724. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44725. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44726. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44727. }
  44728. // Color3
  44729. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44730. switch (loopMode) {
  44731. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44732. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44733. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44734. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44735. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44736. }
  44737. // Matrix
  44738. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44739. switch (loopMode) {
  44740. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44741. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44742. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44743. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44744. }
  44745. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44746. return startValue;
  44747. }
  44748. default:
  44749. break;
  44750. }
  44751. break;
  44752. }
  44753. }
  44754. return this._getKeyValue(keys[keys.length - 1].value);
  44755. };
  44756. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44757. if (blend === void 0) { blend = false; }
  44758. // Set value
  44759. var path;
  44760. var destination;
  44761. var targetPropertyPath = this._animation.targetPropertyPath;
  44762. if (targetPropertyPath.length > 1) {
  44763. var property = this._target[targetPropertyPath[0]];
  44764. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44765. property = property[targetPropertyPath[index]];
  44766. }
  44767. path = targetPropertyPath[targetPropertyPath.length - 1];
  44768. destination = property;
  44769. }
  44770. else {
  44771. path = targetPropertyPath[0];
  44772. destination = this._target;
  44773. }
  44774. // Blending
  44775. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44776. if (!this._originalBlendValue) {
  44777. if (destination[path].clone) {
  44778. this._originalBlendValue = destination[path].clone();
  44779. }
  44780. else {
  44781. this._originalBlendValue = destination[path];
  44782. }
  44783. }
  44784. if (this._originalBlendValue.prototype) {
  44785. if (this._originalBlendValue.prototype.Lerp) {
  44786. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  44787. }
  44788. else {
  44789. destination[path] = currentValue;
  44790. }
  44791. }
  44792. else if (this._originalBlendValue.m) {
  44793. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  44794. }
  44795. else {
  44796. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  44797. }
  44798. this._blendingFactor += this._animation.blendingSpeed;
  44799. }
  44800. else {
  44801. destination[path] = currentValue;
  44802. }
  44803. if (this._target.markAsDirty) {
  44804. this._target.markAsDirty(this._animation.targetProperty);
  44805. }
  44806. };
  44807. RuntimeAnimation.prototype.goToFrame = function (frame) {
  44808. var keys = this._animation.getKeys();
  44809. if (frame < keys[0].frame) {
  44810. frame = keys[0].frame;
  44811. }
  44812. else if (frame > keys[keys.length - 1].frame) {
  44813. frame = keys[keys.length - 1].frame;
  44814. }
  44815. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  44816. this.setValue(currentValue);
  44817. };
  44818. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  44819. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  44820. this._ratioOffset = this._previousRatio - newRatio;
  44821. };
  44822. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  44823. if (blend === void 0) { blend = false; }
  44824. var targetPropertyPath = this._animation.targetPropertyPath;
  44825. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  44826. this._stopped = true;
  44827. return false;
  44828. }
  44829. var returnValue = true;
  44830. var keys = this._animation.getKeys();
  44831. // Adding a start key at frame 0 if missing
  44832. if (keys[0].frame !== 0) {
  44833. var newKey = { frame: 0, value: keys[0].value };
  44834. keys.splice(0, 0, newKey);
  44835. }
  44836. // Check limits
  44837. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44838. from = keys[0].frame;
  44839. }
  44840. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44841. to = keys[keys.length - 1].frame;
  44842. }
  44843. //to and from cannot be the same key
  44844. if (from === to) {
  44845. if (from > keys[0].frame) {
  44846. from--;
  44847. }
  44848. else if (to < keys[keys.length - 1].frame) {
  44849. to++;
  44850. }
  44851. }
  44852. // Compute ratio
  44853. var range = to - from;
  44854. var offsetValue;
  44855. // ratio represents the frame delta between from and to
  44856. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44857. var highLimitValue = 0;
  44858. this._previousDelay = delay;
  44859. this._previousRatio = ratio;
  44860. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44861. returnValue = false;
  44862. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44863. }
  44864. else {
  44865. // Get max value if required
  44866. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44867. var keyOffset = to.toString() + from.toString();
  44868. if (!this._offsetsCache[keyOffset]) {
  44869. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44870. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44871. switch (this._animation.dataType) {
  44872. // Float
  44873. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44874. this._offsetsCache[keyOffset] = toValue - fromValue;
  44875. break;
  44876. // Quaternion
  44877. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44878. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44879. break;
  44880. // Vector3
  44881. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44882. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44883. // Vector2
  44884. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44885. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44886. // Size
  44887. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44888. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44889. // Color3
  44890. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44891. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44892. default:
  44893. break;
  44894. }
  44895. this._highLimitsCache[keyOffset] = toValue;
  44896. }
  44897. highLimitValue = this._highLimitsCache[keyOffset];
  44898. offsetValue = this._offsetsCache[keyOffset];
  44899. }
  44900. }
  44901. if (offsetValue === undefined) {
  44902. switch (this._animation.dataType) {
  44903. // Float
  44904. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44905. offsetValue = 0;
  44906. break;
  44907. // Quaternion
  44908. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44909. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44910. break;
  44911. // Vector3
  44912. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44913. offsetValue = BABYLON.Vector3.Zero();
  44914. break;
  44915. // Vector2
  44916. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44917. offsetValue = BABYLON.Vector2.Zero();
  44918. break;
  44919. // Size
  44920. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44921. offsetValue = BABYLON.Size.Zero();
  44922. break;
  44923. // Color3
  44924. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44925. offsetValue = BABYLON.Color3.Black();
  44926. }
  44927. }
  44928. // Compute value
  44929. var repeatCount = (ratio / range) >> 0;
  44930. var currentFrame = returnValue ? from + ratio % range : to;
  44931. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44932. // Set value
  44933. this.setValue(currentValue);
  44934. // Check events
  44935. var events = this._animation.getEvents();
  44936. for (var index = 0; index < events.length; index++) {
  44937. // Make sure current frame has passed event frame and that event frame is within the current range
  44938. // Also, handle both forward and reverse animations
  44939. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44940. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44941. var event = events[index];
  44942. if (!event.isDone) {
  44943. // If event should be done only once, remove it.
  44944. if (event.onlyOnce) {
  44945. events.splice(index, 1);
  44946. index--;
  44947. }
  44948. event.isDone = true;
  44949. event.action();
  44950. } // Don't do anything if the event has already be done.
  44951. }
  44952. else if (events[index].isDone && !events[index].onlyOnce) {
  44953. // reset event, the animation is looping
  44954. events[index].isDone = false;
  44955. }
  44956. }
  44957. if (!returnValue) {
  44958. this._stopped = true;
  44959. }
  44960. return returnValue;
  44961. };
  44962. return RuntimeAnimation;
  44963. }());
  44964. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44965. })(BABYLON || (BABYLON = {}));
  44966. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44967. var BABYLON;
  44968. (function (BABYLON) {
  44969. var Animatable = /** @class */ (function () {
  44970. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44971. if (fromFrame === void 0) { fromFrame = 0; }
  44972. if (toFrame === void 0) { toFrame = 100; }
  44973. if (loopAnimation === void 0) { loopAnimation = false; }
  44974. if (speedRatio === void 0) { speedRatio = 1.0; }
  44975. this.target = target;
  44976. this.fromFrame = fromFrame;
  44977. this.toFrame = toFrame;
  44978. this.loopAnimation = loopAnimation;
  44979. this.onAnimationEnd = onAnimationEnd;
  44980. this._localDelayOffset = null;
  44981. this._pausedDelay = null;
  44982. this._runtimeAnimations = new Array();
  44983. this._paused = false;
  44984. this._speedRatio = 1;
  44985. this.animationStarted = false;
  44986. if (animations) {
  44987. this.appendAnimations(target, animations);
  44988. }
  44989. this._speedRatio = speedRatio;
  44990. this._scene = scene;
  44991. scene._activeAnimatables.push(this);
  44992. }
  44993. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44994. get: function () {
  44995. return this._speedRatio;
  44996. },
  44997. set: function (value) {
  44998. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44999. var animation = this._runtimeAnimations[index];
  45000. animation._prepareForSpeedRatioChange(value);
  45001. }
  45002. this._speedRatio = value;
  45003. },
  45004. enumerable: true,
  45005. configurable: true
  45006. });
  45007. // Methods
  45008. Animatable.prototype.getAnimations = function () {
  45009. return this._runtimeAnimations;
  45010. };
  45011. Animatable.prototype.appendAnimations = function (target, animations) {
  45012. for (var index = 0; index < animations.length; index++) {
  45013. var animation = animations[index];
  45014. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  45015. }
  45016. };
  45017. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  45018. var runtimeAnimations = this._runtimeAnimations;
  45019. for (var index = 0; index < runtimeAnimations.length; index++) {
  45020. if (runtimeAnimations[index].animation.targetProperty === property) {
  45021. return runtimeAnimations[index].animation;
  45022. }
  45023. }
  45024. return null;
  45025. };
  45026. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  45027. var runtimeAnimations = this._runtimeAnimations;
  45028. for (var index = 0; index < runtimeAnimations.length; index++) {
  45029. if (runtimeAnimations[index].animation.targetProperty === property) {
  45030. return runtimeAnimations[index];
  45031. }
  45032. }
  45033. return null;
  45034. };
  45035. Animatable.prototype.reset = function () {
  45036. var runtimeAnimations = this._runtimeAnimations;
  45037. for (var index = 0; index < runtimeAnimations.length; index++) {
  45038. runtimeAnimations[index].reset();
  45039. }
  45040. // Reset to original value
  45041. for (index = 0; index < runtimeAnimations.length; index++) {
  45042. var animation = runtimeAnimations[index];
  45043. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  45044. }
  45045. this._localDelayOffset = null;
  45046. this._pausedDelay = null;
  45047. };
  45048. Animatable.prototype.enableBlending = function (blendingSpeed) {
  45049. var runtimeAnimations = this._runtimeAnimations;
  45050. for (var index = 0; index < runtimeAnimations.length; index++) {
  45051. runtimeAnimations[index].animation.enableBlending = true;
  45052. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  45053. }
  45054. };
  45055. Animatable.prototype.disableBlending = function () {
  45056. var runtimeAnimations = this._runtimeAnimations;
  45057. for (var index = 0; index < runtimeAnimations.length; index++) {
  45058. runtimeAnimations[index].animation.enableBlending = false;
  45059. }
  45060. };
  45061. Animatable.prototype.goToFrame = function (frame) {
  45062. var runtimeAnimations = this._runtimeAnimations;
  45063. if (runtimeAnimations[0]) {
  45064. var fps = runtimeAnimations[0].animation.framePerSecond;
  45065. var currentFrame = runtimeAnimations[0].currentFrame;
  45066. var adjustTime = frame - currentFrame;
  45067. var delay = adjustTime * 1000 / fps;
  45068. if (this._localDelayOffset === null) {
  45069. this._localDelayOffset = 0;
  45070. }
  45071. this._localDelayOffset -= delay;
  45072. }
  45073. for (var index = 0; index < runtimeAnimations.length; index++) {
  45074. runtimeAnimations[index].goToFrame(frame);
  45075. }
  45076. };
  45077. Animatable.prototype.pause = function () {
  45078. if (this._paused) {
  45079. return;
  45080. }
  45081. this._paused = true;
  45082. };
  45083. Animatable.prototype.restart = function () {
  45084. this._paused = false;
  45085. };
  45086. Animatable.prototype.stop = function (animationName) {
  45087. if (animationName) {
  45088. var idx = this._scene._activeAnimatables.indexOf(this);
  45089. if (idx > -1) {
  45090. var runtimeAnimations = this._runtimeAnimations;
  45091. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  45092. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  45093. continue;
  45094. }
  45095. runtimeAnimations[index].dispose();
  45096. runtimeAnimations.splice(index, 1);
  45097. }
  45098. if (runtimeAnimations.length == 0) {
  45099. this._scene._activeAnimatables.splice(idx, 1);
  45100. if (this.onAnimationEnd) {
  45101. this.onAnimationEnd();
  45102. }
  45103. }
  45104. }
  45105. }
  45106. else {
  45107. var index = this._scene._activeAnimatables.indexOf(this);
  45108. if (index > -1) {
  45109. this._scene._activeAnimatables.splice(index, 1);
  45110. var runtimeAnimations = this._runtimeAnimations;
  45111. for (var index = 0; index < runtimeAnimations.length; index++) {
  45112. runtimeAnimations[index].dispose();
  45113. }
  45114. if (this.onAnimationEnd) {
  45115. this.onAnimationEnd();
  45116. }
  45117. }
  45118. }
  45119. };
  45120. Animatable.prototype._animate = function (delay) {
  45121. if (this._paused) {
  45122. this.animationStarted = false;
  45123. if (this._pausedDelay === null) {
  45124. this._pausedDelay = delay;
  45125. }
  45126. return true;
  45127. }
  45128. if (this._localDelayOffset === null) {
  45129. this._localDelayOffset = delay;
  45130. this._pausedDelay = null;
  45131. }
  45132. else if (this._pausedDelay !== null) {
  45133. this._localDelayOffset += delay - this._pausedDelay;
  45134. this._pausedDelay = null;
  45135. }
  45136. // Animating
  45137. var running = false;
  45138. var runtimeAnimations = this._runtimeAnimations;
  45139. var index;
  45140. for (index = 0; index < runtimeAnimations.length; index++) {
  45141. var animation = runtimeAnimations[index];
  45142. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  45143. running = running || isRunning;
  45144. }
  45145. this.animationStarted = running;
  45146. if (!running) {
  45147. // Remove from active animatables
  45148. index = this._scene._activeAnimatables.indexOf(this);
  45149. this._scene._activeAnimatables.splice(index, 1);
  45150. // Dispose all runtime animations
  45151. for (index = 0; index < runtimeAnimations.length; index++) {
  45152. runtimeAnimations[index].dispose();
  45153. }
  45154. }
  45155. if (!running && this.onAnimationEnd) {
  45156. this.onAnimationEnd();
  45157. this.onAnimationEnd = null;
  45158. }
  45159. return running;
  45160. };
  45161. return Animatable;
  45162. }());
  45163. BABYLON.Animatable = Animatable;
  45164. })(BABYLON || (BABYLON = {}));
  45165. //# sourceMappingURL=babylon.animatable.js.map
  45166. var BABYLON;
  45167. (function (BABYLON) {
  45168. var EasingFunction = /** @class */ (function () {
  45169. function EasingFunction() {
  45170. // Properties
  45171. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  45172. }
  45173. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  45174. get: function () {
  45175. return EasingFunction._EASINGMODE_EASEIN;
  45176. },
  45177. enumerable: true,
  45178. configurable: true
  45179. });
  45180. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  45181. get: function () {
  45182. return EasingFunction._EASINGMODE_EASEOUT;
  45183. },
  45184. enumerable: true,
  45185. configurable: true
  45186. });
  45187. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  45188. get: function () {
  45189. return EasingFunction._EASINGMODE_EASEINOUT;
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. EasingFunction.prototype.setEasingMode = function (easingMode) {
  45195. var n = Math.min(Math.max(easingMode, 0), 2);
  45196. this._easingMode = n;
  45197. };
  45198. EasingFunction.prototype.getEasingMode = function () {
  45199. return this._easingMode;
  45200. };
  45201. EasingFunction.prototype.easeInCore = function (gradient) {
  45202. throw new Error('You must implement this method');
  45203. };
  45204. EasingFunction.prototype.ease = function (gradient) {
  45205. switch (this._easingMode) {
  45206. case EasingFunction.EASINGMODE_EASEIN:
  45207. return this.easeInCore(gradient);
  45208. case EasingFunction.EASINGMODE_EASEOUT:
  45209. return (1 - this.easeInCore(1 - gradient));
  45210. }
  45211. if (gradient >= 0.5) {
  45212. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  45213. }
  45214. return (this.easeInCore(gradient * 2) * 0.5);
  45215. };
  45216. //Statics
  45217. EasingFunction._EASINGMODE_EASEIN = 0;
  45218. EasingFunction._EASINGMODE_EASEOUT = 1;
  45219. EasingFunction._EASINGMODE_EASEINOUT = 2;
  45220. return EasingFunction;
  45221. }());
  45222. BABYLON.EasingFunction = EasingFunction;
  45223. var CircleEase = /** @class */ (function (_super) {
  45224. __extends(CircleEase, _super);
  45225. function CircleEase() {
  45226. return _super !== null && _super.apply(this, arguments) || this;
  45227. }
  45228. CircleEase.prototype.easeInCore = function (gradient) {
  45229. gradient = Math.max(0, Math.min(1, gradient));
  45230. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  45231. };
  45232. return CircleEase;
  45233. }(EasingFunction));
  45234. BABYLON.CircleEase = CircleEase;
  45235. var BackEase = /** @class */ (function (_super) {
  45236. __extends(BackEase, _super);
  45237. function BackEase(amplitude) {
  45238. if (amplitude === void 0) { amplitude = 1; }
  45239. var _this = _super.call(this) || this;
  45240. _this.amplitude = amplitude;
  45241. return _this;
  45242. }
  45243. BackEase.prototype.easeInCore = function (gradient) {
  45244. var num = Math.max(0, this.amplitude);
  45245. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  45246. };
  45247. return BackEase;
  45248. }(EasingFunction));
  45249. BABYLON.BackEase = BackEase;
  45250. var BounceEase = /** @class */ (function (_super) {
  45251. __extends(BounceEase, _super);
  45252. function BounceEase(bounces, bounciness) {
  45253. if (bounces === void 0) { bounces = 3; }
  45254. if (bounciness === void 0) { bounciness = 2; }
  45255. var _this = _super.call(this) || this;
  45256. _this.bounces = bounces;
  45257. _this.bounciness = bounciness;
  45258. return _this;
  45259. }
  45260. BounceEase.prototype.easeInCore = function (gradient) {
  45261. var y = Math.max(0.0, this.bounces);
  45262. var bounciness = this.bounciness;
  45263. if (bounciness <= 1.0) {
  45264. bounciness = 1.001;
  45265. }
  45266. var num9 = Math.pow(bounciness, y);
  45267. var num5 = 1.0 - bounciness;
  45268. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  45269. var num15 = gradient * num4;
  45270. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  45271. var num3 = Math.floor(num65);
  45272. var num13 = num3 + 1.0;
  45273. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  45274. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  45275. var num7 = (num8 + num12) * 0.5;
  45276. var num6 = gradient - num7;
  45277. var num2 = num7 - num8;
  45278. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  45279. };
  45280. return BounceEase;
  45281. }(EasingFunction));
  45282. BABYLON.BounceEase = BounceEase;
  45283. var CubicEase = /** @class */ (function (_super) {
  45284. __extends(CubicEase, _super);
  45285. function CubicEase() {
  45286. return _super !== null && _super.apply(this, arguments) || this;
  45287. }
  45288. CubicEase.prototype.easeInCore = function (gradient) {
  45289. return (gradient * gradient * gradient);
  45290. };
  45291. return CubicEase;
  45292. }(EasingFunction));
  45293. BABYLON.CubicEase = CubicEase;
  45294. var ElasticEase = /** @class */ (function (_super) {
  45295. __extends(ElasticEase, _super);
  45296. function ElasticEase(oscillations, springiness) {
  45297. if (oscillations === void 0) { oscillations = 3; }
  45298. if (springiness === void 0) { springiness = 3; }
  45299. var _this = _super.call(this) || this;
  45300. _this.oscillations = oscillations;
  45301. _this.springiness = springiness;
  45302. return _this;
  45303. }
  45304. ElasticEase.prototype.easeInCore = function (gradient) {
  45305. var num2;
  45306. var num3 = Math.max(0.0, this.oscillations);
  45307. var num = Math.max(0.0, this.springiness);
  45308. if (num == 0) {
  45309. num2 = gradient;
  45310. }
  45311. else {
  45312. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  45313. }
  45314. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  45315. };
  45316. return ElasticEase;
  45317. }(EasingFunction));
  45318. BABYLON.ElasticEase = ElasticEase;
  45319. var ExponentialEase = /** @class */ (function (_super) {
  45320. __extends(ExponentialEase, _super);
  45321. function ExponentialEase(exponent) {
  45322. if (exponent === void 0) { exponent = 2; }
  45323. var _this = _super.call(this) || this;
  45324. _this.exponent = exponent;
  45325. return _this;
  45326. }
  45327. ExponentialEase.prototype.easeInCore = function (gradient) {
  45328. if (this.exponent <= 0) {
  45329. return gradient;
  45330. }
  45331. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  45332. };
  45333. return ExponentialEase;
  45334. }(EasingFunction));
  45335. BABYLON.ExponentialEase = ExponentialEase;
  45336. var PowerEase = /** @class */ (function (_super) {
  45337. __extends(PowerEase, _super);
  45338. function PowerEase(power) {
  45339. if (power === void 0) { power = 2; }
  45340. var _this = _super.call(this) || this;
  45341. _this.power = power;
  45342. return _this;
  45343. }
  45344. PowerEase.prototype.easeInCore = function (gradient) {
  45345. var y = Math.max(0.0, this.power);
  45346. return Math.pow(gradient, y);
  45347. };
  45348. return PowerEase;
  45349. }(EasingFunction));
  45350. BABYLON.PowerEase = PowerEase;
  45351. var QuadraticEase = /** @class */ (function (_super) {
  45352. __extends(QuadraticEase, _super);
  45353. function QuadraticEase() {
  45354. return _super !== null && _super.apply(this, arguments) || this;
  45355. }
  45356. QuadraticEase.prototype.easeInCore = function (gradient) {
  45357. return (gradient * gradient);
  45358. };
  45359. return QuadraticEase;
  45360. }(EasingFunction));
  45361. BABYLON.QuadraticEase = QuadraticEase;
  45362. var QuarticEase = /** @class */ (function (_super) {
  45363. __extends(QuarticEase, _super);
  45364. function QuarticEase() {
  45365. return _super !== null && _super.apply(this, arguments) || this;
  45366. }
  45367. QuarticEase.prototype.easeInCore = function (gradient) {
  45368. return (gradient * gradient * gradient * gradient);
  45369. };
  45370. return QuarticEase;
  45371. }(EasingFunction));
  45372. BABYLON.QuarticEase = QuarticEase;
  45373. var QuinticEase = /** @class */ (function (_super) {
  45374. __extends(QuinticEase, _super);
  45375. function QuinticEase() {
  45376. return _super !== null && _super.apply(this, arguments) || this;
  45377. }
  45378. QuinticEase.prototype.easeInCore = function (gradient) {
  45379. return (gradient * gradient * gradient * gradient * gradient);
  45380. };
  45381. return QuinticEase;
  45382. }(EasingFunction));
  45383. BABYLON.QuinticEase = QuinticEase;
  45384. var SineEase = /** @class */ (function (_super) {
  45385. __extends(SineEase, _super);
  45386. function SineEase() {
  45387. return _super !== null && _super.apply(this, arguments) || this;
  45388. }
  45389. SineEase.prototype.easeInCore = function (gradient) {
  45390. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  45391. };
  45392. return SineEase;
  45393. }(EasingFunction));
  45394. BABYLON.SineEase = SineEase;
  45395. var BezierCurveEase = /** @class */ (function (_super) {
  45396. __extends(BezierCurveEase, _super);
  45397. function BezierCurveEase(x1, y1, x2, y2) {
  45398. if (x1 === void 0) { x1 = 0; }
  45399. if (y1 === void 0) { y1 = 0; }
  45400. if (x2 === void 0) { x2 = 1; }
  45401. if (y2 === void 0) { y2 = 1; }
  45402. var _this = _super.call(this) || this;
  45403. _this.x1 = x1;
  45404. _this.y1 = y1;
  45405. _this.x2 = x2;
  45406. _this.y2 = y2;
  45407. return _this;
  45408. }
  45409. BezierCurveEase.prototype.easeInCore = function (gradient) {
  45410. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  45411. };
  45412. return BezierCurveEase;
  45413. }(EasingFunction));
  45414. BABYLON.BezierCurveEase = BezierCurveEase;
  45415. })(BABYLON || (BABYLON = {}));
  45416. //# sourceMappingURL=babylon.easing.js.map
  45417. var BABYLON;
  45418. (function (BABYLON) {
  45419. var Condition = /** @class */ (function () {
  45420. function Condition(actionManager) {
  45421. this._actionManager = actionManager;
  45422. }
  45423. Condition.prototype.isValid = function () {
  45424. return true;
  45425. };
  45426. Condition.prototype._getProperty = function (propertyPath) {
  45427. return this._actionManager._getProperty(propertyPath);
  45428. };
  45429. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45430. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45431. };
  45432. Condition.prototype.serialize = function () {
  45433. };
  45434. Condition.prototype._serialize = function (serializedCondition) {
  45435. return {
  45436. type: 2,
  45437. children: [],
  45438. name: serializedCondition.name,
  45439. properties: serializedCondition.properties
  45440. };
  45441. };
  45442. return Condition;
  45443. }());
  45444. BABYLON.Condition = Condition;
  45445. var ValueCondition = /** @class */ (function (_super) {
  45446. __extends(ValueCondition, _super);
  45447. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45448. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45449. var _this = _super.call(this, actionManager) || this;
  45450. _this.propertyPath = propertyPath;
  45451. _this.value = value;
  45452. _this.operator = operator;
  45453. _this._target = target;
  45454. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45455. _this._property = _this._getProperty(_this.propertyPath);
  45456. return _this;
  45457. }
  45458. Object.defineProperty(ValueCondition, "IsEqual", {
  45459. get: function () {
  45460. return ValueCondition._IsEqual;
  45461. },
  45462. enumerable: true,
  45463. configurable: true
  45464. });
  45465. Object.defineProperty(ValueCondition, "IsDifferent", {
  45466. get: function () {
  45467. return ValueCondition._IsDifferent;
  45468. },
  45469. enumerable: true,
  45470. configurable: true
  45471. });
  45472. Object.defineProperty(ValueCondition, "IsGreater", {
  45473. get: function () {
  45474. return ValueCondition._IsGreater;
  45475. },
  45476. enumerable: true,
  45477. configurable: true
  45478. });
  45479. Object.defineProperty(ValueCondition, "IsLesser", {
  45480. get: function () {
  45481. return ValueCondition._IsLesser;
  45482. },
  45483. enumerable: true,
  45484. configurable: true
  45485. });
  45486. // Methods
  45487. ValueCondition.prototype.isValid = function () {
  45488. switch (this.operator) {
  45489. case ValueCondition.IsGreater:
  45490. return this._effectiveTarget[this._property] > this.value;
  45491. case ValueCondition.IsLesser:
  45492. return this._effectiveTarget[this._property] < this.value;
  45493. case ValueCondition.IsEqual:
  45494. case ValueCondition.IsDifferent:
  45495. var check;
  45496. if (this.value.equals) {
  45497. check = this.value.equals(this._effectiveTarget[this._property]);
  45498. }
  45499. else {
  45500. check = this.value === this._effectiveTarget[this._property];
  45501. }
  45502. return this.operator === ValueCondition.IsEqual ? check : !check;
  45503. }
  45504. return false;
  45505. };
  45506. ValueCondition.prototype.serialize = function () {
  45507. return this._serialize({
  45508. name: "ValueCondition",
  45509. properties: [
  45510. BABYLON.Action._GetTargetProperty(this._target),
  45511. { name: "propertyPath", value: this.propertyPath },
  45512. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45513. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45514. ]
  45515. });
  45516. };
  45517. ValueCondition.GetOperatorName = function (operator) {
  45518. switch (operator) {
  45519. case ValueCondition._IsEqual: return "IsEqual";
  45520. case ValueCondition._IsDifferent: return "IsDifferent";
  45521. case ValueCondition._IsGreater: return "IsGreater";
  45522. case ValueCondition._IsLesser: return "IsLesser";
  45523. default: return "";
  45524. }
  45525. };
  45526. // Statics
  45527. ValueCondition._IsEqual = 0;
  45528. ValueCondition._IsDifferent = 1;
  45529. ValueCondition._IsGreater = 2;
  45530. ValueCondition._IsLesser = 3;
  45531. return ValueCondition;
  45532. }(Condition));
  45533. BABYLON.ValueCondition = ValueCondition;
  45534. var PredicateCondition = /** @class */ (function (_super) {
  45535. __extends(PredicateCondition, _super);
  45536. function PredicateCondition(actionManager, predicate) {
  45537. var _this = _super.call(this, actionManager) || this;
  45538. _this.predicate = predicate;
  45539. return _this;
  45540. }
  45541. PredicateCondition.prototype.isValid = function () {
  45542. return this.predicate();
  45543. };
  45544. return PredicateCondition;
  45545. }(Condition));
  45546. BABYLON.PredicateCondition = PredicateCondition;
  45547. var StateCondition = /** @class */ (function (_super) {
  45548. __extends(StateCondition, _super);
  45549. function StateCondition(actionManager, target, value) {
  45550. var _this = _super.call(this, actionManager) || this;
  45551. _this.value = value;
  45552. _this._target = target;
  45553. return _this;
  45554. }
  45555. // Methods
  45556. StateCondition.prototype.isValid = function () {
  45557. return this._target.state === this.value;
  45558. };
  45559. StateCondition.prototype.serialize = function () {
  45560. return this._serialize({
  45561. name: "StateCondition",
  45562. properties: [
  45563. BABYLON.Action._GetTargetProperty(this._target),
  45564. { name: "value", value: this.value }
  45565. ]
  45566. });
  45567. };
  45568. return StateCondition;
  45569. }(Condition));
  45570. BABYLON.StateCondition = StateCondition;
  45571. })(BABYLON || (BABYLON = {}));
  45572. //# sourceMappingURL=babylon.condition.js.map
  45573. var BABYLON;
  45574. (function (BABYLON) {
  45575. var Action = /** @class */ (function () {
  45576. function Action(triggerOptions, condition) {
  45577. this.triggerOptions = triggerOptions;
  45578. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45579. if (triggerOptions.parameter) {
  45580. this.trigger = triggerOptions.trigger;
  45581. this._triggerParameter = triggerOptions.parameter;
  45582. }
  45583. else {
  45584. this.trigger = triggerOptions;
  45585. }
  45586. this._nextActiveAction = this;
  45587. this._condition = condition;
  45588. }
  45589. // Methods
  45590. Action.prototype._prepare = function () {
  45591. };
  45592. Action.prototype.getTriggerParameter = function () {
  45593. return this._triggerParameter;
  45594. };
  45595. Action.prototype._executeCurrent = function (evt) {
  45596. if (this._nextActiveAction._condition) {
  45597. var condition = this._nextActiveAction._condition;
  45598. var currentRenderId = this._actionManager.getScene().getRenderId();
  45599. // We cache the current evaluation for the current frame
  45600. if (condition._evaluationId === currentRenderId) {
  45601. if (!condition._currentResult) {
  45602. return;
  45603. }
  45604. }
  45605. else {
  45606. condition._evaluationId = currentRenderId;
  45607. if (!condition.isValid()) {
  45608. condition._currentResult = false;
  45609. return;
  45610. }
  45611. condition._currentResult = true;
  45612. }
  45613. }
  45614. this.onBeforeExecuteObservable.notifyObservers(this);
  45615. this._nextActiveAction.execute(evt);
  45616. this.skipToNextActiveAction();
  45617. };
  45618. Action.prototype.execute = function (evt) {
  45619. };
  45620. Action.prototype.skipToNextActiveAction = function () {
  45621. if (this._nextActiveAction._child) {
  45622. if (!this._nextActiveAction._child._actionManager) {
  45623. this._nextActiveAction._child._actionManager = this._actionManager;
  45624. }
  45625. this._nextActiveAction = this._nextActiveAction._child;
  45626. }
  45627. else {
  45628. this._nextActiveAction = this;
  45629. }
  45630. };
  45631. Action.prototype.then = function (action) {
  45632. this._child = action;
  45633. action._actionManager = this._actionManager;
  45634. action._prepare();
  45635. return action;
  45636. };
  45637. Action.prototype._getProperty = function (propertyPath) {
  45638. return this._actionManager._getProperty(propertyPath);
  45639. };
  45640. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45641. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45642. };
  45643. Action.prototype.serialize = function (parent) {
  45644. };
  45645. // Called by BABYLON.Action objects in serialize(...). Internal use
  45646. Action.prototype._serialize = function (serializedAction, parent) {
  45647. var serializationObject = {
  45648. type: 1,
  45649. children: [],
  45650. name: serializedAction.name,
  45651. properties: serializedAction.properties || []
  45652. };
  45653. // Serialize child
  45654. if (this._child) {
  45655. this._child.serialize(serializationObject);
  45656. }
  45657. // Check if "this" has a condition
  45658. if (this._condition) {
  45659. var serializedCondition = this._condition.serialize();
  45660. serializedCondition.children.push(serializationObject);
  45661. if (parent) {
  45662. parent.children.push(serializedCondition);
  45663. }
  45664. return serializedCondition;
  45665. }
  45666. if (parent) {
  45667. parent.children.push(serializationObject);
  45668. }
  45669. return serializationObject;
  45670. };
  45671. Action._SerializeValueAsString = function (value) {
  45672. if (typeof value === "number") {
  45673. return value.toString();
  45674. }
  45675. if (typeof value === "boolean") {
  45676. return value ? "true" : "false";
  45677. }
  45678. if (value instanceof BABYLON.Vector2) {
  45679. return value.x + ", " + value.y;
  45680. }
  45681. if (value instanceof BABYLON.Vector3) {
  45682. return value.x + ", " + value.y + ", " + value.z;
  45683. }
  45684. if (value instanceof BABYLON.Color3) {
  45685. return value.r + ", " + value.g + ", " + value.b;
  45686. }
  45687. if (value instanceof BABYLON.Color4) {
  45688. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45689. }
  45690. return value; // string
  45691. };
  45692. Action._GetTargetProperty = function (target) {
  45693. return {
  45694. name: "target",
  45695. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45696. : target instanceof BABYLON.Light ? "LightProperties"
  45697. : target instanceof BABYLON.Camera ? "CameraProperties"
  45698. : "SceneProperties",
  45699. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45700. };
  45701. };
  45702. return Action;
  45703. }());
  45704. BABYLON.Action = Action;
  45705. })(BABYLON || (BABYLON = {}));
  45706. //# sourceMappingURL=babylon.action.js.map
  45707. var BABYLON;
  45708. (function (BABYLON) {
  45709. /**
  45710. * ActionEvent is the event beint sent when an action is triggered.
  45711. */
  45712. var ActionEvent = /** @class */ (function () {
  45713. /**
  45714. * @param source The mesh or sprite that triggered the action.
  45715. * @param pointerX The X mouse cursor position at the time of the event
  45716. * @param pointerY The Y mouse cursor position at the time of the event
  45717. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45718. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45719. */
  45720. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45721. this.source = source;
  45722. this.pointerX = pointerX;
  45723. this.pointerY = pointerY;
  45724. this.meshUnderPointer = meshUnderPointer;
  45725. this.sourceEvent = sourceEvent;
  45726. this.additionalData = additionalData;
  45727. }
  45728. /**
  45729. * Helper function to auto-create an ActionEvent from a source mesh.
  45730. * @param source The source mesh that triggered the event
  45731. * @param evt {Event} The original (browser) event
  45732. */
  45733. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45734. var scene = source.getScene();
  45735. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45736. };
  45737. /**
  45738. * Helper function to auto-create an ActionEvent from a source mesh.
  45739. * @param source The source sprite that triggered the event
  45740. * @param scene Scene associated with the sprite
  45741. * @param evt {Event} The original (browser) event
  45742. */
  45743. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45744. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45745. };
  45746. /**
  45747. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45748. * @param scene the scene where the event occurred
  45749. * @param evt {Event} The original (browser) event
  45750. */
  45751. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45752. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45753. };
  45754. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45755. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45756. };
  45757. return ActionEvent;
  45758. }());
  45759. BABYLON.ActionEvent = ActionEvent;
  45760. /**
  45761. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45762. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45763. */
  45764. var ActionManager = /** @class */ (function () {
  45765. function ActionManager(scene) {
  45766. // Members
  45767. this.actions = new Array();
  45768. this.hoverCursor = '';
  45769. this._scene = scene;
  45770. scene._actionManagers.push(this);
  45771. }
  45772. Object.defineProperty(ActionManager, "NothingTrigger", {
  45773. get: function () {
  45774. return ActionManager._NothingTrigger;
  45775. },
  45776. enumerable: true,
  45777. configurable: true
  45778. });
  45779. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45780. get: function () {
  45781. return ActionManager._OnPickTrigger;
  45782. },
  45783. enumerable: true,
  45784. configurable: true
  45785. });
  45786. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45787. get: function () {
  45788. return ActionManager._OnLeftPickTrigger;
  45789. },
  45790. enumerable: true,
  45791. configurable: true
  45792. });
  45793. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45794. get: function () {
  45795. return ActionManager._OnRightPickTrigger;
  45796. },
  45797. enumerable: true,
  45798. configurable: true
  45799. });
  45800. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45801. get: function () {
  45802. return ActionManager._OnCenterPickTrigger;
  45803. },
  45804. enumerable: true,
  45805. configurable: true
  45806. });
  45807. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45808. get: function () {
  45809. return ActionManager._OnPickDownTrigger;
  45810. },
  45811. enumerable: true,
  45812. configurable: true
  45813. });
  45814. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45815. get: function () {
  45816. return ActionManager._OnDoublePickTrigger;
  45817. },
  45818. enumerable: true,
  45819. configurable: true
  45820. });
  45821. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45822. get: function () {
  45823. return ActionManager._OnPickUpTrigger;
  45824. },
  45825. enumerable: true,
  45826. configurable: true
  45827. });
  45828. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45829. /// This trigger will only be raised if you also declared a OnPickDown
  45830. get: function () {
  45831. return ActionManager._OnPickOutTrigger;
  45832. },
  45833. enumerable: true,
  45834. configurable: true
  45835. });
  45836. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45837. get: function () {
  45838. return ActionManager._OnLongPressTrigger;
  45839. },
  45840. enumerable: true,
  45841. configurable: true
  45842. });
  45843. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45844. get: function () {
  45845. return ActionManager._OnPointerOverTrigger;
  45846. },
  45847. enumerable: true,
  45848. configurable: true
  45849. });
  45850. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45851. get: function () {
  45852. return ActionManager._OnPointerOutTrigger;
  45853. },
  45854. enumerable: true,
  45855. configurable: true
  45856. });
  45857. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45858. get: function () {
  45859. return ActionManager._OnEveryFrameTrigger;
  45860. },
  45861. enumerable: true,
  45862. configurable: true
  45863. });
  45864. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45865. get: function () {
  45866. return ActionManager._OnIntersectionEnterTrigger;
  45867. },
  45868. enumerable: true,
  45869. configurable: true
  45870. });
  45871. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45872. get: function () {
  45873. return ActionManager._OnIntersectionExitTrigger;
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45879. get: function () {
  45880. return ActionManager._OnKeyDownTrigger;
  45881. },
  45882. enumerable: true,
  45883. configurable: true
  45884. });
  45885. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45886. get: function () {
  45887. return ActionManager._OnKeyUpTrigger;
  45888. },
  45889. enumerable: true,
  45890. configurable: true
  45891. });
  45892. // Methods
  45893. ActionManager.prototype.dispose = function () {
  45894. var index = this._scene._actionManagers.indexOf(this);
  45895. for (var i = 0; i < this.actions.length; i++) {
  45896. var action = this.actions[i];
  45897. ActionManager.Triggers[action.trigger]--;
  45898. if (ActionManager.Triggers[action.trigger] === 0) {
  45899. delete ActionManager.Triggers[action.trigger];
  45900. }
  45901. }
  45902. if (index > -1) {
  45903. this._scene._actionManagers.splice(index, 1);
  45904. }
  45905. };
  45906. ActionManager.prototype.getScene = function () {
  45907. return this._scene;
  45908. };
  45909. /**
  45910. * Does this action manager handles actions of any of the given triggers
  45911. * @param {number[]} triggers - the triggers to be tested
  45912. * @return {boolean} whether one (or more) of the triggers is handeled
  45913. */
  45914. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45915. for (var index = 0; index < this.actions.length; index++) {
  45916. var action = this.actions[index];
  45917. if (triggers.indexOf(action.trigger) > -1) {
  45918. return true;
  45919. }
  45920. }
  45921. return false;
  45922. };
  45923. /**
  45924. * Does this action manager handles actions of a given trigger
  45925. * @param {number} trigger - the trigger to be tested
  45926. * @return {boolean} whether the trigger is handeled
  45927. */
  45928. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45929. for (var index = 0; index < this.actions.length; index++) {
  45930. var action = this.actions[index];
  45931. if (action.trigger === trigger) {
  45932. return true;
  45933. }
  45934. }
  45935. return false;
  45936. };
  45937. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45938. /**
  45939. * Does this action manager has pointer triggers
  45940. * @return {boolean} whether or not it has pointer triggers
  45941. */
  45942. get: function () {
  45943. for (var index = 0; index < this.actions.length; index++) {
  45944. var action = this.actions[index];
  45945. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45946. return true;
  45947. }
  45948. }
  45949. return false;
  45950. },
  45951. enumerable: true,
  45952. configurable: true
  45953. });
  45954. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45955. /**
  45956. * Does this action manager has pick triggers
  45957. * @return {boolean} whether or not it has pick triggers
  45958. */
  45959. get: function () {
  45960. for (var index = 0; index < this.actions.length; index++) {
  45961. var action = this.actions[index];
  45962. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45963. return true;
  45964. }
  45965. }
  45966. return false;
  45967. },
  45968. enumerable: true,
  45969. configurable: true
  45970. });
  45971. Object.defineProperty(ActionManager, "HasTriggers", {
  45972. /**
  45973. * Does exist one action manager with at least one trigger
  45974. * @return {boolean} whether or not it exists one action manager with one trigger
  45975. **/
  45976. get: function () {
  45977. for (var t in ActionManager.Triggers) {
  45978. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45979. return true;
  45980. }
  45981. }
  45982. return false;
  45983. },
  45984. enumerable: true,
  45985. configurable: true
  45986. });
  45987. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45988. /**
  45989. * Does exist one action manager with at least one pick trigger
  45990. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45991. **/
  45992. get: function () {
  45993. for (var t in ActionManager.Triggers) {
  45994. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45995. var t_int = parseInt(t);
  45996. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45997. return true;
  45998. }
  45999. }
  46000. }
  46001. return false;
  46002. },
  46003. enumerable: true,
  46004. configurable: true
  46005. });
  46006. /**
  46007. * Does exist one action manager that handles actions of a given trigger
  46008. * @param {number} trigger - the trigger to be tested
  46009. * @return {boolean} whether the trigger is handeled by at least one action manager
  46010. **/
  46011. ActionManager.HasSpecificTrigger = function (trigger) {
  46012. for (var t in ActionManager.Triggers) {
  46013. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46014. var t_int = parseInt(t);
  46015. if (t_int === trigger) {
  46016. return true;
  46017. }
  46018. }
  46019. }
  46020. return false;
  46021. };
  46022. /**
  46023. * Registers an action to this action manager
  46024. * @param {BABYLON.Action} action - the action to be registered
  46025. * @return {BABYLON.Action} the action amended (prepared) after registration
  46026. */
  46027. ActionManager.prototype.registerAction = function (action) {
  46028. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46029. if (this.getScene().actionManager !== this) {
  46030. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46031. return null;
  46032. }
  46033. }
  46034. this.actions.push(action);
  46035. if (ActionManager.Triggers[action.trigger]) {
  46036. ActionManager.Triggers[action.trigger]++;
  46037. }
  46038. else {
  46039. ActionManager.Triggers[action.trigger] = 1;
  46040. }
  46041. action._actionManager = this;
  46042. action._prepare();
  46043. return action;
  46044. };
  46045. /**
  46046. * Unregisters an action to this action manager
  46047. * @param action The action to be unregistered
  46048. * @return whether the action has been unregistered
  46049. */
  46050. ActionManager.prototype.unregisterAction = function (action) {
  46051. var index = this.actions.indexOf(action);
  46052. if (index !== -1) {
  46053. this.actions.splice(index, 1);
  46054. ActionManager.Triggers[action.trigger] -= 1;
  46055. if (ActionManager.Triggers[action.trigger] === 0) {
  46056. delete ActionManager.Triggers[action.trigger];
  46057. }
  46058. delete action._actionManager;
  46059. return true;
  46060. }
  46061. return false;
  46062. };
  46063. /**
  46064. * Process a specific trigger
  46065. * @param {number} trigger - the trigger to process
  46066. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46067. */
  46068. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46069. for (var index = 0; index < this.actions.length; index++) {
  46070. var action = this.actions[index];
  46071. if (action.trigger === trigger) {
  46072. if (evt) {
  46073. if (trigger === ActionManager.OnKeyUpTrigger
  46074. || trigger === ActionManager.OnKeyDownTrigger) {
  46075. var parameter = action.getTriggerParameter();
  46076. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46077. if (!parameter.toLowerCase) {
  46078. continue;
  46079. }
  46080. var lowerCase = parameter.toLowerCase();
  46081. if (lowerCase !== evt.sourceEvent.key) {
  46082. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46083. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46084. if (actualkey !== lowerCase) {
  46085. continue;
  46086. }
  46087. }
  46088. }
  46089. }
  46090. }
  46091. action._executeCurrent(evt);
  46092. }
  46093. }
  46094. };
  46095. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46096. var properties = propertyPath.split(".");
  46097. for (var index = 0; index < properties.length - 1; index++) {
  46098. target = target[properties[index]];
  46099. }
  46100. return target;
  46101. };
  46102. ActionManager.prototype._getProperty = function (propertyPath) {
  46103. var properties = propertyPath.split(".");
  46104. return properties[properties.length - 1];
  46105. };
  46106. ActionManager.prototype.serialize = function (name) {
  46107. var root = {
  46108. children: new Array(),
  46109. name: name,
  46110. type: 3,
  46111. properties: new Array() // Empty for root but required
  46112. };
  46113. for (var i = 0; i < this.actions.length; i++) {
  46114. var triggerObject = {
  46115. type: 0,
  46116. children: new Array(),
  46117. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46118. properties: new Array()
  46119. };
  46120. var triggerOptions = this.actions[i].triggerOptions;
  46121. if (triggerOptions && typeof triggerOptions !== "number") {
  46122. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46123. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46124. }
  46125. else {
  46126. var parameter = {};
  46127. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46128. if (triggerOptions.parameter.mesh) {
  46129. parameter._meshId = triggerOptions.parameter.mesh.id;
  46130. }
  46131. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46132. }
  46133. }
  46134. // Serialize child action, recursively
  46135. this.actions[i].serialize(triggerObject);
  46136. // Add serialized trigger
  46137. root.children.push(triggerObject);
  46138. }
  46139. return root;
  46140. };
  46141. ActionManager.Parse = function (parsedActions, object, scene) {
  46142. var actionManager = new ActionManager(scene);
  46143. if (object === null)
  46144. scene.actionManager = actionManager;
  46145. else
  46146. object.actionManager = actionManager;
  46147. // instanciate a new object
  46148. var instanciate = function (name, params) {
  46149. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  46150. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  46151. newInstance.constructor.apply(newInstance, params);
  46152. return newInstance;
  46153. };
  46154. var parseParameter = function (name, value, target, propertyPath) {
  46155. if (propertyPath === null) {
  46156. // String, boolean or float
  46157. var floatValue = parseFloat(value);
  46158. if (value === "true" || value === "false")
  46159. return value === "true";
  46160. else
  46161. return isNaN(floatValue) ? value : floatValue;
  46162. }
  46163. var effectiveTarget = propertyPath.split(".");
  46164. var values = value.split(",");
  46165. // Get effective Target
  46166. for (var i = 0; i < effectiveTarget.length; i++) {
  46167. target = target[effectiveTarget[i]];
  46168. }
  46169. // Return appropriate value with its type
  46170. if (typeof (target) === "boolean")
  46171. return values[0] === "true";
  46172. if (typeof (target) === "string")
  46173. return values[0];
  46174. // Parameters with multiple values such as Vector3 etc.
  46175. var split = new Array();
  46176. for (var i = 0; i < values.length; i++)
  46177. split.push(parseFloat(values[i]));
  46178. if (target instanceof BABYLON.Vector3)
  46179. return BABYLON.Vector3.FromArray(split);
  46180. if (target instanceof BABYLON.Vector4)
  46181. return BABYLON.Vector4.FromArray(split);
  46182. if (target instanceof BABYLON.Color3)
  46183. return BABYLON.Color3.FromArray(split);
  46184. if (target instanceof BABYLON.Color4)
  46185. return BABYLON.Color4.FromArray(split);
  46186. return parseFloat(values[0]);
  46187. };
  46188. // traverse graph per trigger
  46189. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46190. if (combineArray === void 0) { combineArray = null; }
  46191. if (parsedAction.detached)
  46192. return;
  46193. var parameters = new Array();
  46194. var target = null;
  46195. var propertyPath = null;
  46196. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46197. // Parameters
  46198. if (parsedAction.type === 2)
  46199. parameters.push(actionManager);
  46200. else
  46201. parameters.push(trigger);
  46202. if (combine) {
  46203. var actions = new Array();
  46204. for (var j = 0; j < parsedAction.combine.length; j++) {
  46205. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46206. }
  46207. parameters.push(actions);
  46208. }
  46209. else {
  46210. for (var i = 0; i < parsedAction.properties.length; i++) {
  46211. var value = parsedAction.properties[i].value;
  46212. var name = parsedAction.properties[i].name;
  46213. var targetType = parsedAction.properties[i].targetType;
  46214. if (name === "target")
  46215. if (targetType !== null && targetType === "SceneProperties")
  46216. value = target = scene;
  46217. else
  46218. value = target = scene.getNodeByName(value);
  46219. else if (name === "parent")
  46220. value = scene.getNodeByName(value);
  46221. else if (name === "sound")
  46222. value = scene.getSoundByName(value);
  46223. else if (name !== "propertyPath") {
  46224. if (parsedAction.type === 2 && name === "operator")
  46225. value = BABYLON.ValueCondition[value];
  46226. else
  46227. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46228. }
  46229. else {
  46230. propertyPath = value;
  46231. }
  46232. parameters.push(value);
  46233. }
  46234. }
  46235. if (combineArray === null) {
  46236. parameters.push(condition);
  46237. }
  46238. else {
  46239. parameters.push(null);
  46240. }
  46241. // If interpolate value action
  46242. if (parsedAction.name === "InterpolateValueAction") {
  46243. var param = parameters[parameters.length - 2];
  46244. parameters[parameters.length - 1] = param;
  46245. parameters[parameters.length - 2] = condition;
  46246. }
  46247. // Action or condition(s) and not CombineAction
  46248. var newAction = instanciate(parsedAction.name, parameters);
  46249. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46250. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46251. if (action)
  46252. action.then(nothing);
  46253. else
  46254. actionManager.registerAction(nothing);
  46255. action = nothing;
  46256. }
  46257. if (combineArray === null) {
  46258. if (newAction instanceof BABYLON.Condition) {
  46259. condition = newAction;
  46260. newAction = action;
  46261. }
  46262. else {
  46263. condition = null;
  46264. if (action)
  46265. action.then(newAction);
  46266. else
  46267. actionManager.registerAction(newAction);
  46268. }
  46269. }
  46270. else {
  46271. combineArray.push(newAction);
  46272. }
  46273. for (var i = 0; i < parsedAction.children.length; i++)
  46274. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46275. };
  46276. // triggers
  46277. for (var i = 0; i < parsedActions.children.length; i++) {
  46278. var triggerParams;
  46279. var trigger = parsedActions.children[i];
  46280. if (trigger.properties.length > 0) {
  46281. var param = trigger.properties[0].value;
  46282. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46283. if (value._meshId) {
  46284. value.mesh = scene.getMeshByID(value._meshId);
  46285. }
  46286. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  46287. }
  46288. else
  46289. triggerParams = ActionManager[trigger.name];
  46290. for (var j = 0; j < trigger.children.length; j++) {
  46291. if (!trigger.detached)
  46292. traverse(trigger.children[j], triggerParams, null, null);
  46293. }
  46294. }
  46295. };
  46296. ActionManager.GetTriggerName = function (trigger) {
  46297. switch (trigger) {
  46298. case 0: return "NothingTrigger";
  46299. case 1: return "OnPickTrigger";
  46300. case 2: return "OnLeftPickTrigger";
  46301. case 3: return "OnRightPickTrigger";
  46302. case 4: return "OnCenterPickTrigger";
  46303. case 5: return "OnPickDownTrigger";
  46304. case 6: return "OnPickUpTrigger";
  46305. case 7: return "OnLongPressTrigger";
  46306. case 8: return "OnPointerOverTrigger";
  46307. case 9: return "OnPointerOutTrigger";
  46308. case 10: return "OnEveryFrameTrigger";
  46309. case 11: return "OnIntersectionEnterTrigger";
  46310. case 12: return "OnIntersectionExitTrigger";
  46311. case 13: return "OnKeyDownTrigger";
  46312. case 14: return "OnKeyUpTrigger";
  46313. case 15: return "OnPickOutTrigger";
  46314. default: return "";
  46315. }
  46316. };
  46317. // Statics
  46318. ActionManager._NothingTrigger = 0;
  46319. ActionManager._OnPickTrigger = 1;
  46320. ActionManager._OnLeftPickTrigger = 2;
  46321. ActionManager._OnRightPickTrigger = 3;
  46322. ActionManager._OnCenterPickTrigger = 4;
  46323. ActionManager._OnPickDownTrigger = 5;
  46324. ActionManager._OnDoublePickTrigger = 6;
  46325. ActionManager._OnPickUpTrigger = 7;
  46326. ActionManager._OnLongPressTrigger = 8;
  46327. ActionManager._OnPointerOverTrigger = 9;
  46328. ActionManager._OnPointerOutTrigger = 10;
  46329. ActionManager._OnEveryFrameTrigger = 11;
  46330. ActionManager._OnIntersectionEnterTrigger = 12;
  46331. ActionManager._OnIntersectionExitTrigger = 13;
  46332. ActionManager._OnKeyDownTrigger = 14;
  46333. ActionManager._OnKeyUpTrigger = 15;
  46334. ActionManager._OnPickOutTrigger = 16;
  46335. ActionManager.Triggers = {};
  46336. return ActionManager;
  46337. }());
  46338. BABYLON.ActionManager = ActionManager;
  46339. })(BABYLON || (BABYLON = {}));
  46340. //# sourceMappingURL=babylon.actionManager.js.map
  46341. var BABYLON;
  46342. (function (BABYLON) {
  46343. var InterpolateValueAction = /** @class */ (function (_super) {
  46344. __extends(InterpolateValueAction, _super);
  46345. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46346. if (duration === void 0) { duration = 1000; }
  46347. var _this = _super.call(this, triggerOptions, condition) || this;
  46348. _this.propertyPath = propertyPath;
  46349. _this.value = value;
  46350. _this.duration = duration;
  46351. _this.stopOtherAnimations = stopOtherAnimations;
  46352. _this.onInterpolationDone = onInterpolationDone;
  46353. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  46354. _this._target = _this._effectiveTarget = target;
  46355. return _this;
  46356. }
  46357. InterpolateValueAction.prototype._prepare = function () {
  46358. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46359. this._property = this._getProperty(this.propertyPath);
  46360. };
  46361. InterpolateValueAction.prototype.execute = function () {
  46362. var _this = this;
  46363. var scene = this._actionManager.getScene();
  46364. var keys = [
  46365. {
  46366. frame: 0,
  46367. value: this._effectiveTarget[this._property]
  46368. }, {
  46369. frame: 100,
  46370. value: this.value
  46371. }
  46372. ];
  46373. var dataType;
  46374. if (typeof this.value === "number") {
  46375. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46376. }
  46377. else if (this.value instanceof BABYLON.Color3) {
  46378. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46379. }
  46380. else if (this.value instanceof BABYLON.Vector3) {
  46381. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46382. }
  46383. else if (this.value instanceof BABYLON.Matrix) {
  46384. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46385. }
  46386. else if (this.value instanceof BABYLON.Quaternion) {
  46387. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46388. }
  46389. else {
  46390. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46391. return;
  46392. }
  46393. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46394. animation.setKeys(keys);
  46395. if (this.stopOtherAnimations) {
  46396. scene.stopAnimation(this._effectiveTarget);
  46397. }
  46398. var wrapper = function () {
  46399. _this.onInterpolationDoneObservable.notifyObservers(_this);
  46400. if (_this.onInterpolationDone) {
  46401. _this.onInterpolationDone();
  46402. }
  46403. };
  46404. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  46405. };
  46406. InterpolateValueAction.prototype.serialize = function (parent) {
  46407. return _super.prototype._serialize.call(this, {
  46408. name: "InterpolateValueAction",
  46409. properties: [
  46410. BABYLON.Action._GetTargetProperty(this._target),
  46411. { name: "propertyPath", value: this.propertyPath },
  46412. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46413. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46414. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46415. ]
  46416. }, parent);
  46417. };
  46418. return InterpolateValueAction;
  46419. }(BABYLON.Action));
  46420. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46421. })(BABYLON || (BABYLON = {}));
  46422. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46423. var BABYLON;
  46424. (function (BABYLON) {
  46425. var SwitchBooleanAction = /** @class */ (function (_super) {
  46426. __extends(SwitchBooleanAction, _super);
  46427. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46428. var _this = _super.call(this, triggerOptions, condition) || this;
  46429. _this.propertyPath = propertyPath;
  46430. _this._target = _this._effectiveTarget = target;
  46431. return _this;
  46432. }
  46433. SwitchBooleanAction.prototype._prepare = function () {
  46434. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46435. this._property = this._getProperty(this.propertyPath);
  46436. };
  46437. SwitchBooleanAction.prototype.execute = function () {
  46438. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46439. };
  46440. SwitchBooleanAction.prototype.serialize = function (parent) {
  46441. return _super.prototype._serialize.call(this, {
  46442. name: "SwitchBooleanAction",
  46443. properties: [
  46444. BABYLON.Action._GetTargetProperty(this._target),
  46445. { name: "propertyPath", value: this.propertyPath }
  46446. ]
  46447. }, parent);
  46448. };
  46449. return SwitchBooleanAction;
  46450. }(BABYLON.Action));
  46451. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46452. var SetStateAction = /** @class */ (function (_super) {
  46453. __extends(SetStateAction, _super);
  46454. function SetStateAction(triggerOptions, target, value, condition) {
  46455. var _this = _super.call(this, triggerOptions, condition) || this;
  46456. _this.value = value;
  46457. _this._target = target;
  46458. return _this;
  46459. }
  46460. SetStateAction.prototype.execute = function () {
  46461. this._target.state = this.value;
  46462. };
  46463. SetStateAction.prototype.serialize = function (parent) {
  46464. return _super.prototype._serialize.call(this, {
  46465. name: "SetStateAction",
  46466. properties: [
  46467. BABYLON.Action._GetTargetProperty(this._target),
  46468. { name: "value", value: this.value }
  46469. ]
  46470. }, parent);
  46471. };
  46472. return SetStateAction;
  46473. }(BABYLON.Action));
  46474. BABYLON.SetStateAction = SetStateAction;
  46475. var SetValueAction = /** @class */ (function (_super) {
  46476. __extends(SetValueAction, _super);
  46477. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46478. var _this = _super.call(this, triggerOptions, condition) || this;
  46479. _this.propertyPath = propertyPath;
  46480. _this.value = value;
  46481. _this._target = _this._effectiveTarget = target;
  46482. return _this;
  46483. }
  46484. SetValueAction.prototype._prepare = function () {
  46485. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46486. this._property = this._getProperty(this.propertyPath);
  46487. };
  46488. SetValueAction.prototype.execute = function () {
  46489. this._effectiveTarget[this._property] = this.value;
  46490. if (this._target.markAsDirty) {
  46491. this._target.markAsDirty(this._property);
  46492. }
  46493. };
  46494. SetValueAction.prototype.serialize = function (parent) {
  46495. return _super.prototype._serialize.call(this, {
  46496. name: "SetValueAction",
  46497. properties: [
  46498. BABYLON.Action._GetTargetProperty(this._target),
  46499. { name: "propertyPath", value: this.propertyPath },
  46500. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46501. ]
  46502. }, parent);
  46503. };
  46504. return SetValueAction;
  46505. }(BABYLON.Action));
  46506. BABYLON.SetValueAction = SetValueAction;
  46507. var IncrementValueAction = /** @class */ (function (_super) {
  46508. __extends(IncrementValueAction, _super);
  46509. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46510. var _this = _super.call(this, triggerOptions, condition) || this;
  46511. _this.propertyPath = propertyPath;
  46512. _this.value = value;
  46513. _this._target = _this._effectiveTarget = target;
  46514. return _this;
  46515. }
  46516. IncrementValueAction.prototype._prepare = function () {
  46517. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46518. this._property = this._getProperty(this.propertyPath);
  46519. if (typeof this._effectiveTarget[this._property] !== "number") {
  46520. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46521. }
  46522. };
  46523. IncrementValueAction.prototype.execute = function () {
  46524. this._effectiveTarget[this._property] += this.value;
  46525. if (this._target.markAsDirty) {
  46526. this._target.markAsDirty(this._property);
  46527. }
  46528. };
  46529. IncrementValueAction.prototype.serialize = function (parent) {
  46530. return _super.prototype._serialize.call(this, {
  46531. name: "IncrementValueAction",
  46532. properties: [
  46533. BABYLON.Action._GetTargetProperty(this._target),
  46534. { name: "propertyPath", value: this.propertyPath },
  46535. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46536. ]
  46537. }, parent);
  46538. };
  46539. return IncrementValueAction;
  46540. }(BABYLON.Action));
  46541. BABYLON.IncrementValueAction = IncrementValueAction;
  46542. var PlayAnimationAction = /** @class */ (function (_super) {
  46543. __extends(PlayAnimationAction, _super);
  46544. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46545. var _this = _super.call(this, triggerOptions, condition) || this;
  46546. _this.from = from;
  46547. _this.to = to;
  46548. _this.loop = loop;
  46549. _this._target = target;
  46550. return _this;
  46551. }
  46552. PlayAnimationAction.prototype._prepare = function () {
  46553. };
  46554. PlayAnimationAction.prototype.execute = function () {
  46555. var scene = this._actionManager.getScene();
  46556. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46557. };
  46558. PlayAnimationAction.prototype.serialize = function (parent) {
  46559. return _super.prototype._serialize.call(this, {
  46560. name: "PlayAnimationAction",
  46561. properties: [
  46562. BABYLON.Action._GetTargetProperty(this._target),
  46563. { name: "from", value: String(this.from) },
  46564. { name: "to", value: String(this.to) },
  46565. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46566. ]
  46567. }, parent);
  46568. };
  46569. return PlayAnimationAction;
  46570. }(BABYLON.Action));
  46571. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46572. var StopAnimationAction = /** @class */ (function (_super) {
  46573. __extends(StopAnimationAction, _super);
  46574. function StopAnimationAction(triggerOptions, target, condition) {
  46575. var _this = _super.call(this, triggerOptions, condition) || this;
  46576. _this._target = target;
  46577. return _this;
  46578. }
  46579. StopAnimationAction.prototype._prepare = function () {
  46580. };
  46581. StopAnimationAction.prototype.execute = function () {
  46582. var scene = this._actionManager.getScene();
  46583. scene.stopAnimation(this._target);
  46584. };
  46585. StopAnimationAction.prototype.serialize = function (parent) {
  46586. return _super.prototype._serialize.call(this, {
  46587. name: "StopAnimationAction",
  46588. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46589. }, parent);
  46590. };
  46591. return StopAnimationAction;
  46592. }(BABYLON.Action));
  46593. BABYLON.StopAnimationAction = StopAnimationAction;
  46594. var DoNothingAction = /** @class */ (function (_super) {
  46595. __extends(DoNothingAction, _super);
  46596. function DoNothingAction(triggerOptions, condition) {
  46597. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46598. return _super.call(this, triggerOptions, condition) || this;
  46599. }
  46600. DoNothingAction.prototype.execute = function () {
  46601. };
  46602. DoNothingAction.prototype.serialize = function (parent) {
  46603. return _super.prototype._serialize.call(this, {
  46604. name: "DoNothingAction",
  46605. properties: []
  46606. }, parent);
  46607. };
  46608. return DoNothingAction;
  46609. }(BABYLON.Action));
  46610. BABYLON.DoNothingAction = DoNothingAction;
  46611. var CombineAction = /** @class */ (function (_super) {
  46612. __extends(CombineAction, _super);
  46613. function CombineAction(triggerOptions, children, condition) {
  46614. var _this = _super.call(this, triggerOptions, condition) || this;
  46615. _this.children = children;
  46616. return _this;
  46617. }
  46618. CombineAction.prototype._prepare = function () {
  46619. for (var index = 0; index < this.children.length; index++) {
  46620. this.children[index]._actionManager = this._actionManager;
  46621. this.children[index]._prepare();
  46622. }
  46623. };
  46624. CombineAction.prototype.execute = function (evt) {
  46625. for (var index = 0; index < this.children.length; index++) {
  46626. this.children[index].execute(evt);
  46627. }
  46628. };
  46629. CombineAction.prototype.serialize = function (parent) {
  46630. var serializationObject = _super.prototype._serialize.call(this, {
  46631. name: "CombineAction",
  46632. properties: [],
  46633. combine: []
  46634. }, parent);
  46635. for (var i = 0; i < this.children.length; i++) {
  46636. serializationObject.combine.push(this.children[i].serialize(null));
  46637. }
  46638. return serializationObject;
  46639. };
  46640. return CombineAction;
  46641. }(BABYLON.Action));
  46642. BABYLON.CombineAction = CombineAction;
  46643. var ExecuteCodeAction = /** @class */ (function (_super) {
  46644. __extends(ExecuteCodeAction, _super);
  46645. function ExecuteCodeAction(triggerOptions, func, condition) {
  46646. var _this = _super.call(this, triggerOptions, condition) || this;
  46647. _this.func = func;
  46648. return _this;
  46649. }
  46650. ExecuteCodeAction.prototype.execute = function (evt) {
  46651. this.func(evt);
  46652. };
  46653. return ExecuteCodeAction;
  46654. }(BABYLON.Action));
  46655. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46656. var SetParentAction = /** @class */ (function (_super) {
  46657. __extends(SetParentAction, _super);
  46658. function SetParentAction(triggerOptions, target, parent, condition) {
  46659. var _this = _super.call(this, triggerOptions, condition) || this;
  46660. _this._target = target;
  46661. _this._parent = parent;
  46662. return _this;
  46663. }
  46664. SetParentAction.prototype._prepare = function () {
  46665. };
  46666. SetParentAction.prototype.execute = function () {
  46667. if (this._target.parent === this._parent) {
  46668. return;
  46669. }
  46670. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46671. invertParentWorldMatrix.invert();
  46672. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46673. this._target.parent = this._parent;
  46674. };
  46675. SetParentAction.prototype.serialize = function (parent) {
  46676. return _super.prototype._serialize.call(this, {
  46677. name: "SetParentAction",
  46678. properties: [
  46679. BABYLON.Action._GetTargetProperty(this._target),
  46680. BABYLON.Action._GetTargetProperty(this._parent),
  46681. ]
  46682. }, parent);
  46683. };
  46684. return SetParentAction;
  46685. }(BABYLON.Action));
  46686. BABYLON.SetParentAction = SetParentAction;
  46687. var PlaySoundAction = /** @class */ (function (_super) {
  46688. __extends(PlaySoundAction, _super);
  46689. function PlaySoundAction(triggerOptions, sound, condition) {
  46690. var _this = _super.call(this, triggerOptions, condition) || this;
  46691. _this._sound = sound;
  46692. return _this;
  46693. }
  46694. PlaySoundAction.prototype._prepare = function () {
  46695. };
  46696. PlaySoundAction.prototype.execute = function () {
  46697. if (this._sound !== undefined)
  46698. this._sound.play();
  46699. };
  46700. PlaySoundAction.prototype.serialize = function (parent) {
  46701. return _super.prototype._serialize.call(this, {
  46702. name: "PlaySoundAction",
  46703. properties: [{ name: "sound", value: this._sound.name }]
  46704. }, parent);
  46705. };
  46706. return PlaySoundAction;
  46707. }(BABYLON.Action));
  46708. BABYLON.PlaySoundAction = PlaySoundAction;
  46709. var StopSoundAction = /** @class */ (function (_super) {
  46710. __extends(StopSoundAction, _super);
  46711. function StopSoundAction(triggerOptions, sound, condition) {
  46712. var _this = _super.call(this, triggerOptions, condition) || this;
  46713. _this._sound = sound;
  46714. return _this;
  46715. }
  46716. StopSoundAction.prototype._prepare = function () {
  46717. };
  46718. StopSoundAction.prototype.execute = function () {
  46719. if (this._sound !== undefined)
  46720. this._sound.stop();
  46721. };
  46722. StopSoundAction.prototype.serialize = function (parent) {
  46723. return _super.prototype._serialize.call(this, {
  46724. name: "StopSoundAction",
  46725. properties: [{ name: "sound", value: this._sound.name }]
  46726. }, parent);
  46727. };
  46728. return StopSoundAction;
  46729. }(BABYLON.Action));
  46730. BABYLON.StopSoundAction = StopSoundAction;
  46731. })(BABYLON || (BABYLON = {}));
  46732. //# sourceMappingURL=babylon.directActions.js.map
  46733. var BABYLON;
  46734. (function (BABYLON) {
  46735. var SpriteManager = /** @class */ (function () {
  46736. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46737. if (epsilon === void 0) { epsilon = 0.01; }
  46738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46739. this.name = name;
  46740. this.sprites = new Array();
  46741. this.renderingGroupId = 0;
  46742. this.layerMask = 0x0FFFFFFF;
  46743. this.fogEnabled = true;
  46744. this.isPickable = false;
  46745. /**
  46746. * An event triggered when the manager is disposed.
  46747. * @type {BABYLON.Observable}
  46748. */
  46749. this.onDisposeObservable = new BABYLON.Observable();
  46750. this._vertexBuffers = {};
  46751. this._capacity = capacity;
  46752. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46753. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46754. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46755. if (cellSize.width && cellSize.height) {
  46756. this.cellWidth = cellSize.width;
  46757. this.cellHeight = cellSize.height;
  46758. }
  46759. else if (cellSize !== undefined) {
  46760. this.cellWidth = cellSize;
  46761. this.cellHeight = cellSize;
  46762. }
  46763. else {
  46764. return;
  46765. }
  46766. this._epsilon = epsilon;
  46767. this._scene = scene;
  46768. this._scene.spriteManagers.push(this);
  46769. var indices = [];
  46770. var index = 0;
  46771. for (var count = 0; count < capacity; count++) {
  46772. indices.push(index);
  46773. indices.push(index + 1);
  46774. indices.push(index + 2);
  46775. indices.push(index);
  46776. indices.push(index + 2);
  46777. indices.push(index + 3);
  46778. index += 4;
  46779. }
  46780. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46781. // VBO
  46782. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  46783. this._vertexData = new Float32Array(capacity * 16 * 4);
  46784. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  46785. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  46786. var options = this._buffer.createVertexBuffer("options", 4, 4);
  46787. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  46788. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  46789. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46790. this._vertexBuffers["options"] = options;
  46791. this._vertexBuffers["cellInfo"] = cellInfo;
  46792. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46793. // Effects
  46794. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  46795. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  46796. }
  46797. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  46798. set: function (callback) {
  46799. if (this._onDisposeObserver) {
  46800. this.onDisposeObservable.remove(this._onDisposeObserver);
  46801. }
  46802. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46803. },
  46804. enumerable: true,
  46805. configurable: true
  46806. });
  46807. Object.defineProperty(SpriteManager.prototype, "texture", {
  46808. get: function () {
  46809. return this._spriteTexture;
  46810. },
  46811. set: function (value) {
  46812. this._spriteTexture = value;
  46813. },
  46814. enumerable: true,
  46815. configurable: true
  46816. });
  46817. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  46818. var arrayOffset = index * 16;
  46819. if (offsetX === 0)
  46820. offsetX = this._epsilon;
  46821. else if (offsetX === 1)
  46822. offsetX = 1 - this._epsilon;
  46823. if (offsetY === 0)
  46824. offsetY = this._epsilon;
  46825. else if (offsetY === 1)
  46826. offsetY = 1 - this._epsilon;
  46827. this._vertexData[arrayOffset] = sprite.position.x;
  46828. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46829. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46830. this._vertexData[arrayOffset + 3] = sprite.angle;
  46831. this._vertexData[arrayOffset + 4] = sprite.width;
  46832. this._vertexData[arrayOffset + 5] = sprite.height;
  46833. this._vertexData[arrayOffset + 6] = offsetX;
  46834. this._vertexData[arrayOffset + 7] = offsetY;
  46835. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46836. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46837. var offset = (sprite.cellIndex / rowSize) >> 0;
  46838. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46839. this._vertexData[arrayOffset + 11] = offset;
  46840. // Color
  46841. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46842. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46843. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46844. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46845. };
  46846. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46847. var count = Math.min(this._capacity, this.sprites.length);
  46848. var min = BABYLON.Vector3.Zero();
  46849. var max = BABYLON.Vector3.Zero();
  46850. var distance = Number.MAX_VALUE;
  46851. var currentSprite = null;
  46852. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46853. var cameraView = camera.getViewMatrix();
  46854. for (var index = 0; index < count; index++) {
  46855. var sprite = this.sprites[index];
  46856. if (!sprite) {
  46857. continue;
  46858. }
  46859. if (predicate) {
  46860. if (!predicate(sprite)) {
  46861. continue;
  46862. }
  46863. }
  46864. else if (!sprite.isPickable) {
  46865. continue;
  46866. }
  46867. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46868. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46869. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46870. if (ray.intersectsBoxMinMax(min, max)) {
  46871. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46872. if (distance > currentDistance) {
  46873. distance = currentDistance;
  46874. currentSprite = sprite;
  46875. if (fastCheck) {
  46876. break;
  46877. }
  46878. }
  46879. }
  46880. }
  46881. if (currentSprite) {
  46882. var result = new BABYLON.PickingInfo();
  46883. result.hit = true;
  46884. result.pickedSprite = currentSprite;
  46885. result.distance = distance;
  46886. return result;
  46887. }
  46888. return null;
  46889. };
  46890. SpriteManager.prototype.render = function () {
  46891. // Check
  46892. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46893. return;
  46894. var engine = this._scene.getEngine();
  46895. var baseSize = this._spriteTexture.getBaseSize();
  46896. // Sprites
  46897. var deltaTime = engine.getDeltaTime();
  46898. var max = Math.min(this._capacity, this.sprites.length);
  46899. var rowSize = baseSize.width / this.cellWidth;
  46900. var offset = 0;
  46901. for (var index = 0; index < max; index++) {
  46902. var sprite = this.sprites[index];
  46903. if (!sprite) {
  46904. continue;
  46905. }
  46906. sprite._animate(deltaTime);
  46907. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46908. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46909. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46910. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46911. }
  46912. this._buffer.update(this._vertexData);
  46913. // Render
  46914. var effect = this._effectBase;
  46915. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46916. effect = this._effectFog;
  46917. }
  46918. engine.enableEffect(effect);
  46919. var viewMatrix = this._scene.getViewMatrix();
  46920. effect.setTexture("diffuseSampler", this._spriteTexture);
  46921. effect.setMatrix("view", viewMatrix);
  46922. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46923. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46924. // Fog
  46925. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46926. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46927. effect.setColor3("vFogColor", this._scene.fogColor);
  46928. }
  46929. // VBOs
  46930. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46931. // Draw order
  46932. engine.setDepthFunctionToLessOrEqual();
  46933. effect.setBool("alphaTest", true);
  46934. engine.setColorWrite(false);
  46935. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46936. engine.setColorWrite(true);
  46937. effect.setBool("alphaTest", false);
  46938. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46939. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46940. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46941. };
  46942. SpriteManager.prototype.dispose = function () {
  46943. if (this._buffer) {
  46944. this._buffer.dispose();
  46945. this._buffer = null;
  46946. }
  46947. if (this._indexBuffer) {
  46948. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46949. this._indexBuffer = null;
  46950. }
  46951. if (this._spriteTexture) {
  46952. this._spriteTexture.dispose();
  46953. this._spriteTexture = null;
  46954. }
  46955. // Remove from scene
  46956. var index = this._scene.spriteManagers.indexOf(this);
  46957. this._scene.spriteManagers.splice(index, 1);
  46958. // Callback
  46959. this.onDisposeObservable.notifyObservers(this);
  46960. this.onDisposeObservable.clear();
  46961. };
  46962. return SpriteManager;
  46963. }());
  46964. BABYLON.SpriteManager = SpriteManager;
  46965. })(BABYLON || (BABYLON = {}));
  46966. //# sourceMappingURL=babylon.spriteManager.js.map
  46967. var BABYLON;
  46968. (function (BABYLON) {
  46969. var Sprite = /** @class */ (function () {
  46970. function Sprite(name, manager) {
  46971. this.name = name;
  46972. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46973. this.width = 1.0;
  46974. this.height = 1.0;
  46975. this.angle = 0;
  46976. this.cellIndex = 0;
  46977. this.invertU = 0;
  46978. this.invertV = 0;
  46979. this.animations = new Array();
  46980. this.isPickable = false;
  46981. this._animationStarted = false;
  46982. this._loopAnimation = false;
  46983. this._fromIndex = 0;
  46984. this._toIndex = 0;
  46985. this._delay = 0;
  46986. this._direction = 1;
  46987. this._time = 0;
  46988. this._manager = manager;
  46989. this._manager.sprites.push(this);
  46990. this.position = BABYLON.Vector3.Zero();
  46991. }
  46992. Object.defineProperty(Sprite.prototype, "size", {
  46993. get: function () {
  46994. return this.width;
  46995. },
  46996. set: function (value) {
  46997. this.width = value;
  46998. this.height = value;
  46999. },
  47000. enumerable: true,
  47001. configurable: true
  47002. });
  47003. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  47004. this._fromIndex = from;
  47005. this._toIndex = to;
  47006. this._loopAnimation = loop;
  47007. this._delay = delay;
  47008. this._animationStarted = true;
  47009. this._direction = from < to ? 1 : -1;
  47010. this.cellIndex = from;
  47011. this._time = 0;
  47012. this._onAnimationEnd = onAnimationEnd;
  47013. };
  47014. Sprite.prototype.stopAnimation = function () {
  47015. this._animationStarted = false;
  47016. };
  47017. Sprite.prototype._animate = function (deltaTime) {
  47018. if (!this._animationStarted)
  47019. return;
  47020. this._time += deltaTime;
  47021. if (this._time > this._delay) {
  47022. this._time = this._time % this._delay;
  47023. this.cellIndex += this._direction;
  47024. if (this.cellIndex > this._toIndex) {
  47025. if (this._loopAnimation) {
  47026. this.cellIndex = this._fromIndex;
  47027. }
  47028. else {
  47029. this.cellIndex = this._toIndex;
  47030. this._animationStarted = false;
  47031. if (this._onAnimationEnd) {
  47032. this._onAnimationEnd();
  47033. }
  47034. if (this.disposeWhenFinishedAnimating) {
  47035. this.dispose();
  47036. }
  47037. }
  47038. }
  47039. }
  47040. };
  47041. Sprite.prototype.dispose = function () {
  47042. for (var i = 0; i < this._manager.sprites.length; i++) {
  47043. if (this._manager.sprites[i] == this) {
  47044. this._manager.sprites.splice(i, 1);
  47045. }
  47046. }
  47047. };
  47048. return Sprite;
  47049. }());
  47050. BABYLON.Sprite = Sprite;
  47051. })(BABYLON || (BABYLON = {}));
  47052. //# sourceMappingURL=babylon.sprite.js.map
  47053. var BABYLON;
  47054. (function (BABYLON) {
  47055. var IntersectionInfo = /** @class */ (function () {
  47056. function IntersectionInfo(bu, bv, distance) {
  47057. this.bu = bu;
  47058. this.bv = bv;
  47059. this.distance = distance;
  47060. this.faceId = 0;
  47061. this.subMeshId = 0;
  47062. }
  47063. return IntersectionInfo;
  47064. }());
  47065. BABYLON.IntersectionInfo = IntersectionInfo;
  47066. var PickingInfo = /** @class */ (function () {
  47067. function PickingInfo() {
  47068. this.hit = false;
  47069. this.distance = 0;
  47070. this.pickedPoint = null;
  47071. this.pickedMesh = null;
  47072. this.bu = 0;
  47073. this.bv = 0;
  47074. this.faceId = -1;
  47075. this.subMeshId = 0;
  47076. this.pickedSprite = null;
  47077. }
  47078. // Methods
  47079. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  47080. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  47081. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  47082. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  47083. return null;
  47084. }
  47085. var indices = this.pickedMesh.getIndices();
  47086. if (!indices) {
  47087. return null;
  47088. }
  47089. var result;
  47090. if (useVerticesNormals) {
  47091. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47092. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  47093. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  47094. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  47095. normal0 = normal0.scale(this.bu);
  47096. normal1 = normal1.scale(this.bv);
  47097. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  47098. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  47099. }
  47100. else {
  47101. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47102. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  47103. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  47104. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  47105. var p1p2 = vertex1.subtract(vertex2);
  47106. var p3p2 = vertex3.subtract(vertex2);
  47107. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  47108. }
  47109. if (useWorldCoordinates) {
  47110. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  47111. }
  47112. return BABYLON.Vector3.Normalize(result);
  47113. };
  47114. PickingInfo.prototype.getTextureCoordinates = function () {
  47115. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47116. return null;
  47117. }
  47118. var indices = this.pickedMesh.getIndices();
  47119. if (!indices) {
  47120. return null;
  47121. }
  47122. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47123. if (!uvs) {
  47124. return null;
  47125. }
  47126. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  47127. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  47128. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  47129. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  47130. uv1 = uv1.scale(this.bu);
  47131. uv2 = uv2.scale(this.bv);
  47132. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  47133. };
  47134. return PickingInfo;
  47135. }());
  47136. BABYLON.PickingInfo = PickingInfo;
  47137. })(BABYLON || (BABYLON = {}));
  47138. //# sourceMappingURL=babylon.pickingInfo.js.map
  47139. var BABYLON;
  47140. (function (BABYLON) {
  47141. var Ray = /** @class */ (function () {
  47142. function Ray(origin, direction, length) {
  47143. if (length === void 0) { length = Number.MAX_VALUE; }
  47144. this.origin = origin;
  47145. this.direction = direction;
  47146. this.length = length;
  47147. }
  47148. // Methods
  47149. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  47150. var d = 0.0;
  47151. var maxValue = Number.MAX_VALUE;
  47152. var inv;
  47153. var min;
  47154. var max;
  47155. var temp;
  47156. if (Math.abs(this.direction.x) < 0.0000001) {
  47157. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  47158. return false;
  47159. }
  47160. }
  47161. else {
  47162. inv = 1.0 / this.direction.x;
  47163. min = (minimum.x - this.origin.x) * inv;
  47164. max = (maximum.x - this.origin.x) * inv;
  47165. if (max === -Infinity) {
  47166. max = Infinity;
  47167. }
  47168. if (min > max) {
  47169. temp = min;
  47170. min = max;
  47171. max = temp;
  47172. }
  47173. d = Math.max(min, d);
  47174. maxValue = Math.min(max, maxValue);
  47175. if (d > maxValue) {
  47176. return false;
  47177. }
  47178. }
  47179. if (Math.abs(this.direction.y) < 0.0000001) {
  47180. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  47181. return false;
  47182. }
  47183. }
  47184. else {
  47185. inv = 1.0 / this.direction.y;
  47186. min = (minimum.y - this.origin.y) * inv;
  47187. max = (maximum.y - this.origin.y) * inv;
  47188. if (max === -Infinity) {
  47189. max = Infinity;
  47190. }
  47191. if (min > max) {
  47192. temp = min;
  47193. min = max;
  47194. max = temp;
  47195. }
  47196. d = Math.max(min, d);
  47197. maxValue = Math.min(max, maxValue);
  47198. if (d > maxValue) {
  47199. return false;
  47200. }
  47201. }
  47202. if (Math.abs(this.direction.z) < 0.0000001) {
  47203. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  47204. return false;
  47205. }
  47206. }
  47207. else {
  47208. inv = 1.0 / this.direction.z;
  47209. min = (minimum.z - this.origin.z) * inv;
  47210. max = (maximum.z - this.origin.z) * inv;
  47211. if (max === -Infinity) {
  47212. max = Infinity;
  47213. }
  47214. if (min > max) {
  47215. temp = min;
  47216. min = max;
  47217. max = temp;
  47218. }
  47219. d = Math.max(min, d);
  47220. maxValue = Math.min(max, maxValue);
  47221. if (d > maxValue) {
  47222. return false;
  47223. }
  47224. }
  47225. return true;
  47226. };
  47227. Ray.prototype.intersectsBox = function (box) {
  47228. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  47229. };
  47230. Ray.prototype.intersectsSphere = function (sphere) {
  47231. var x = sphere.center.x - this.origin.x;
  47232. var y = sphere.center.y - this.origin.y;
  47233. var z = sphere.center.z - this.origin.z;
  47234. var pyth = (x * x) + (y * y) + (z * z);
  47235. var rr = sphere.radius * sphere.radius;
  47236. if (pyth <= rr) {
  47237. return true;
  47238. }
  47239. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  47240. if (dot < 0.0) {
  47241. return false;
  47242. }
  47243. var temp = pyth - (dot * dot);
  47244. return temp <= rr;
  47245. };
  47246. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  47247. if (!this._edge1) {
  47248. this._edge1 = BABYLON.Vector3.Zero();
  47249. this._edge2 = BABYLON.Vector3.Zero();
  47250. this._pvec = BABYLON.Vector3.Zero();
  47251. this._tvec = BABYLON.Vector3.Zero();
  47252. this._qvec = BABYLON.Vector3.Zero();
  47253. }
  47254. vertex1.subtractToRef(vertex0, this._edge1);
  47255. vertex2.subtractToRef(vertex0, this._edge2);
  47256. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  47257. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  47258. if (det === 0) {
  47259. return null;
  47260. }
  47261. var invdet = 1 / det;
  47262. this.origin.subtractToRef(vertex0, this._tvec);
  47263. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  47264. if (bu < 0 || bu > 1.0) {
  47265. return null;
  47266. }
  47267. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  47268. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  47269. if (bv < 0 || bu + bv > 1.0) {
  47270. return null;
  47271. }
  47272. //check if the distance is longer than the predefined length.
  47273. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  47274. if (distance > this.length) {
  47275. return null;
  47276. }
  47277. return new BABYLON.IntersectionInfo(bu, bv, distance);
  47278. };
  47279. Ray.prototype.intersectsPlane = function (plane) {
  47280. var distance;
  47281. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  47282. if (Math.abs(result1) < 9.99999997475243E-07) {
  47283. return null;
  47284. }
  47285. else {
  47286. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  47287. distance = (-plane.d - result2) / result1;
  47288. if (distance < 0.0) {
  47289. if (distance < -9.99999997475243E-07) {
  47290. return null;
  47291. }
  47292. else {
  47293. return 0;
  47294. }
  47295. }
  47296. return distance;
  47297. }
  47298. };
  47299. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  47300. var tm = BABYLON.Tmp.Matrix[0];
  47301. mesh.getWorldMatrix().invertToRef(tm);
  47302. if (this._tmpRay) {
  47303. Ray.TransformToRef(this, tm, this._tmpRay);
  47304. }
  47305. else {
  47306. this._tmpRay = Ray.Transform(this, tm);
  47307. }
  47308. return mesh.intersects(this._tmpRay, fastCheck);
  47309. };
  47310. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  47311. if (results) {
  47312. results.length = 0;
  47313. }
  47314. else {
  47315. results = [];
  47316. }
  47317. for (var i = 0; i < meshes.length; i++) {
  47318. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  47319. if (pickInfo.hit) {
  47320. results.push(pickInfo);
  47321. }
  47322. }
  47323. results.sort(this._comparePickingInfo);
  47324. return results;
  47325. };
  47326. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  47327. if (pickingInfoA.distance < pickingInfoB.distance) {
  47328. return -1;
  47329. }
  47330. else if (pickingInfoA.distance > pickingInfoB.distance) {
  47331. return 1;
  47332. }
  47333. else {
  47334. return 0;
  47335. }
  47336. };
  47337. /**
  47338. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  47339. * @param sega the first point of the segment to test the intersection against
  47340. * @param segb the second point of the segment to test the intersection against
  47341. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  47342. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  47343. */
  47344. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  47345. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  47346. var u = segb.subtract(sega);
  47347. var v = rsegb.subtract(this.origin);
  47348. var w = sega.subtract(this.origin);
  47349. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  47350. var b = BABYLON.Vector3.Dot(u, v);
  47351. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  47352. var d = BABYLON.Vector3.Dot(u, w);
  47353. var e = BABYLON.Vector3.Dot(v, w);
  47354. var D = a * c - b * b; // always >= 0
  47355. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  47356. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  47357. // compute the line parameters of the two closest points
  47358. if (D < Ray.smallnum) {
  47359. sN = 0.0; // force using point P0 on segment S1
  47360. sD = 1.0; // to prevent possible division by 0.0 later
  47361. tN = e;
  47362. tD = c;
  47363. }
  47364. else {
  47365. sN = (b * e - c * d);
  47366. tN = (a * e - b * d);
  47367. if (sN < 0.0) {
  47368. sN = 0.0;
  47369. tN = e;
  47370. tD = c;
  47371. }
  47372. else if (sN > sD) {
  47373. sN = sD;
  47374. tN = e + b;
  47375. tD = c;
  47376. }
  47377. }
  47378. if (tN < 0.0) {
  47379. tN = 0.0;
  47380. // recompute sc for this edge
  47381. if (-d < 0.0) {
  47382. sN = 0.0;
  47383. }
  47384. else if (-d > a)
  47385. sN = sD;
  47386. else {
  47387. sN = -d;
  47388. sD = a;
  47389. }
  47390. }
  47391. else if (tN > tD) {
  47392. tN = tD;
  47393. // recompute sc for this edge
  47394. if ((-d + b) < 0.0) {
  47395. sN = 0;
  47396. }
  47397. else if ((-d + b) > a) {
  47398. sN = sD;
  47399. }
  47400. else {
  47401. sN = (-d + b);
  47402. sD = a;
  47403. }
  47404. }
  47405. // finally do the division to get sc and tc
  47406. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  47407. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  47408. // get the difference of the two closest points
  47409. var qtc = v.multiplyByFloats(tc, tc, tc);
  47410. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  47411. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  47412. if (isIntersected) {
  47413. return qtc.length();
  47414. }
  47415. return -1;
  47416. };
  47417. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47418. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  47419. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  47420. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  47421. this.direction.normalize();
  47422. return this;
  47423. };
  47424. // Statics
  47425. Ray.Zero = function () {
  47426. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  47427. };
  47428. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47429. var result = Ray.Zero();
  47430. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  47431. };
  47432. /**
  47433. * 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
  47434. * transformed to the given world matrix.
  47435. * @param origin The origin point
  47436. * @param end The end point
  47437. * @param world a matrix to transform the ray to. Default is the identity matrix.
  47438. */
  47439. Ray.CreateNewFromTo = function (origin, end, world) {
  47440. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  47441. var direction = end.subtract(origin);
  47442. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  47443. direction.normalize();
  47444. return Ray.Transform(new Ray(origin, direction, length), world);
  47445. };
  47446. Ray.Transform = function (ray, matrix) {
  47447. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  47448. Ray.TransformToRef(ray, matrix, result);
  47449. return result;
  47450. };
  47451. Ray.TransformToRef = function (ray, matrix, result) {
  47452. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  47453. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  47454. result.length = ray.length;
  47455. var dir = result.direction;
  47456. var len = dir.length();
  47457. if (!(len === 0 || len === 1)) {
  47458. var num = 1.0 / len;
  47459. dir.x *= num;
  47460. dir.y *= num;
  47461. dir.z *= num;
  47462. result.length *= len;
  47463. }
  47464. };
  47465. Ray.smallnum = 0.00000001;
  47466. Ray.rayl = 10e8;
  47467. return Ray;
  47468. }());
  47469. BABYLON.Ray = Ray;
  47470. })(BABYLON || (BABYLON = {}));
  47471. //# sourceMappingURL=babylon.ray.js.map
  47472. var BABYLON;
  47473. (function (BABYLON) {
  47474. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  47475. if (boxMin.x > sphereCenter.x + sphereRadius)
  47476. return false;
  47477. if (sphereCenter.x - sphereRadius > boxMax.x)
  47478. return false;
  47479. if (boxMin.y > sphereCenter.y + sphereRadius)
  47480. return false;
  47481. if (sphereCenter.y - sphereRadius > boxMax.y)
  47482. return false;
  47483. if (boxMin.z > sphereCenter.z + sphereRadius)
  47484. return false;
  47485. if (sphereCenter.z - sphereRadius > boxMax.z)
  47486. return false;
  47487. return true;
  47488. };
  47489. var getLowestRoot = (function () {
  47490. var result = { root: 0, found: false };
  47491. return function (a, b, c, maxR) {
  47492. result.root = 0;
  47493. result.found = false;
  47494. var determinant = b * b - 4.0 * a * c;
  47495. if (determinant < 0)
  47496. return result;
  47497. var sqrtD = Math.sqrt(determinant);
  47498. var r1 = (-b - sqrtD) / (2.0 * a);
  47499. var r2 = (-b + sqrtD) / (2.0 * a);
  47500. if (r1 > r2) {
  47501. var temp = r2;
  47502. r2 = r1;
  47503. r1 = temp;
  47504. }
  47505. if (r1 > 0 && r1 < maxR) {
  47506. result.root = r1;
  47507. result.found = true;
  47508. return result;
  47509. }
  47510. if (r2 > 0 && r2 < maxR) {
  47511. result.root = r2;
  47512. result.found = true;
  47513. return result;
  47514. }
  47515. return result;
  47516. };
  47517. })();
  47518. var Collider = /** @class */ (function () {
  47519. function Collider() {
  47520. this._collisionPoint = BABYLON.Vector3.Zero();
  47521. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47522. this._tempVector = BABYLON.Vector3.Zero();
  47523. this._tempVector2 = BABYLON.Vector3.Zero();
  47524. this._tempVector3 = BABYLON.Vector3.Zero();
  47525. this._tempVector4 = BABYLON.Vector3.Zero();
  47526. this._edge = BABYLON.Vector3.Zero();
  47527. this._baseToVertex = BABYLON.Vector3.Zero();
  47528. this._destinationPoint = BABYLON.Vector3.Zero();
  47529. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47530. this._displacementVector = BABYLON.Vector3.Zero();
  47531. this._radius = BABYLON.Vector3.One();
  47532. this._retry = 0;
  47533. this._basePointWorld = BABYLON.Vector3.Zero();
  47534. this._velocityWorld = BABYLON.Vector3.Zero();
  47535. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47536. this._collisionMask = -1;
  47537. }
  47538. Object.defineProperty(Collider.prototype, "collisionMask", {
  47539. get: function () {
  47540. return this._collisionMask;
  47541. },
  47542. set: function (mask) {
  47543. this._collisionMask = !isNaN(mask) ? mask : -1;
  47544. },
  47545. enumerable: true,
  47546. configurable: true
  47547. });
  47548. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47549. /**
  47550. * Gets the plane normal used to compute the sliding response (in local space)
  47551. */
  47552. get: function () {
  47553. return this._slidePlaneNormal;
  47554. },
  47555. enumerable: true,
  47556. configurable: true
  47557. });
  47558. // Methods
  47559. Collider.prototype._initialize = function (source, dir, e) {
  47560. this._velocity = dir;
  47561. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47562. this._basePoint = source;
  47563. source.multiplyToRef(this._radius, this._basePointWorld);
  47564. dir.multiplyToRef(this._radius, this._velocityWorld);
  47565. this._velocityWorldLength = this._velocityWorld.length();
  47566. this._epsilon = e;
  47567. this.collisionFound = false;
  47568. };
  47569. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47570. pa.subtractToRef(point, this._tempVector);
  47571. pb.subtractToRef(point, this._tempVector2);
  47572. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47573. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47574. if (d < 0)
  47575. return false;
  47576. pc.subtractToRef(point, this._tempVector3);
  47577. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47578. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47579. if (d < 0)
  47580. return false;
  47581. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47582. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47583. return d >= 0;
  47584. };
  47585. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47586. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47587. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47588. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47589. return false;
  47590. }
  47591. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47592. return false;
  47593. return true;
  47594. };
  47595. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47596. var t0;
  47597. var embeddedInPlane = false;
  47598. //defensive programming, actually not needed.
  47599. if (!trianglePlaneArray) {
  47600. trianglePlaneArray = [];
  47601. }
  47602. if (!trianglePlaneArray[faceIndex]) {
  47603. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47604. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47605. }
  47606. var trianglePlane = trianglePlaneArray[faceIndex];
  47607. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47608. return;
  47609. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47610. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47611. if (normalDotVelocity == 0) {
  47612. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47613. return;
  47614. embeddedInPlane = true;
  47615. t0 = 0;
  47616. }
  47617. else {
  47618. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47619. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47620. if (t0 > t1) {
  47621. var temp = t1;
  47622. t1 = t0;
  47623. t0 = temp;
  47624. }
  47625. if (t0 > 1.0 || t1 < 0.0)
  47626. return;
  47627. if (t0 < 0)
  47628. t0 = 0;
  47629. if (t0 > 1.0)
  47630. t0 = 1.0;
  47631. }
  47632. this._collisionPoint.copyFromFloats(0, 0, 0);
  47633. var found = false;
  47634. var t = 1.0;
  47635. if (!embeddedInPlane) {
  47636. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47637. this._velocity.scaleToRef(t0, this._tempVector);
  47638. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47639. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47640. found = true;
  47641. t = t0;
  47642. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47643. }
  47644. }
  47645. if (!found) {
  47646. var velocitySquaredLength = this._velocity.lengthSquared();
  47647. var a = velocitySquaredLength;
  47648. this._basePoint.subtractToRef(p1, this._tempVector);
  47649. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47650. var c = this._tempVector.lengthSquared() - 1.0;
  47651. var lowestRoot = getLowestRoot(a, b, c, t);
  47652. if (lowestRoot.found) {
  47653. t = lowestRoot.root;
  47654. found = true;
  47655. this._collisionPoint.copyFrom(p1);
  47656. }
  47657. this._basePoint.subtractToRef(p2, this._tempVector);
  47658. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47659. c = this._tempVector.lengthSquared() - 1.0;
  47660. lowestRoot = getLowestRoot(a, b, c, t);
  47661. if (lowestRoot.found) {
  47662. t = lowestRoot.root;
  47663. found = true;
  47664. this._collisionPoint.copyFrom(p2);
  47665. }
  47666. this._basePoint.subtractToRef(p3, this._tempVector);
  47667. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47668. c = this._tempVector.lengthSquared() - 1.0;
  47669. lowestRoot = getLowestRoot(a, b, c, t);
  47670. if (lowestRoot.found) {
  47671. t = lowestRoot.root;
  47672. found = true;
  47673. this._collisionPoint.copyFrom(p3);
  47674. }
  47675. p2.subtractToRef(p1, this._edge);
  47676. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47677. var edgeSquaredLength = this._edge.lengthSquared();
  47678. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47679. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47680. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47681. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47682. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47683. lowestRoot = getLowestRoot(a, b, c, t);
  47684. if (lowestRoot.found) {
  47685. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47686. if (f >= 0.0 && f <= 1.0) {
  47687. t = lowestRoot.root;
  47688. found = true;
  47689. this._edge.scaleInPlace(f);
  47690. p1.addToRef(this._edge, this._collisionPoint);
  47691. }
  47692. }
  47693. p3.subtractToRef(p2, this._edge);
  47694. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47695. edgeSquaredLength = this._edge.lengthSquared();
  47696. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47697. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47698. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47699. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47700. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47701. lowestRoot = getLowestRoot(a, b, c, t);
  47702. if (lowestRoot.found) {
  47703. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47704. if (f >= 0.0 && f <= 1.0) {
  47705. t = lowestRoot.root;
  47706. found = true;
  47707. this._edge.scaleInPlace(f);
  47708. p2.addToRef(this._edge, this._collisionPoint);
  47709. }
  47710. }
  47711. p1.subtractToRef(p3, this._edge);
  47712. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47713. edgeSquaredLength = this._edge.lengthSquared();
  47714. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47715. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47716. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47717. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47718. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47719. lowestRoot = getLowestRoot(a, b, c, t);
  47720. if (lowestRoot.found) {
  47721. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47722. if (f >= 0.0 && f <= 1.0) {
  47723. t = lowestRoot.root;
  47724. found = true;
  47725. this._edge.scaleInPlace(f);
  47726. p3.addToRef(this._edge, this._collisionPoint);
  47727. }
  47728. }
  47729. }
  47730. if (found) {
  47731. var distToCollision = t * this._velocity.length();
  47732. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47733. if (!this.intersectionPoint) {
  47734. this.intersectionPoint = this._collisionPoint.clone();
  47735. }
  47736. else {
  47737. this.intersectionPoint.copyFrom(this._collisionPoint);
  47738. }
  47739. this._nearestDistance = distToCollision;
  47740. this.collisionFound = true;
  47741. }
  47742. }
  47743. };
  47744. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47745. for (var i = indexStart; i < indexEnd; i += 3) {
  47746. var p1 = pts[indices[i] - decal];
  47747. var p2 = pts[indices[i + 1] - decal];
  47748. var p3 = pts[indices[i + 2] - decal];
  47749. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47750. }
  47751. };
  47752. Collider.prototype._getResponse = function (pos, vel) {
  47753. pos.addToRef(vel, this._destinationPoint);
  47754. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47755. this._basePoint.addToRef(vel, pos);
  47756. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47757. this._slidePlaneNormal.normalize();
  47758. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47759. pos.addInPlace(this._displacementVector);
  47760. this.intersectionPoint.addInPlace(this._displacementVector);
  47761. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47762. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47763. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47764. };
  47765. return Collider;
  47766. }());
  47767. BABYLON.Collider = Collider;
  47768. })(BABYLON || (BABYLON = {}));
  47769. //# sourceMappingURL=babylon.collider.js.map
  47770. var BABYLON;
  47771. (function (BABYLON) {
  47772. //WebWorker code will be inserted to this variable.
  47773. BABYLON.CollisionWorker = "";
  47774. var WorkerTaskType;
  47775. (function (WorkerTaskType) {
  47776. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47777. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47778. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47779. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47780. var WorkerReplyType;
  47781. (function (WorkerReplyType) {
  47782. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  47783. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  47784. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  47785. var CollisionCoordinatorWorker = /** @class */ (function () {
  47786. function CollisionCoordinatorWorker() {
  47787. var _this = this;
  47788. this._scaledPosition = BABYLON.Vector3.Zero();
  47789. this._scaledVelocity = BABYLON.Vector3.Zero();
  47790. this.onMeshUpdated = function (transformNode) {
  47791. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  47792. };
  47793. this.onGeometryUpdated = function (geometry) {
  47794. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  47795. };
  47796. this._afterRender = function () {
  47797. if (!_this._init)
  47798. return;
  47799. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  47800. return;
  47801. }
  47802. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  47803. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  47804. if (_this._runningUpdated > 4) {
  47805. return;
  47806. }
  47807. ++_this._runningUpdated;
  47808. var payload = {
  47809. updatedMeshes: _this._addUpdateMeshesList,
  47810. updatedGeometries: _this._addUpdateGeometriesList,
  47811. removedGeometries: _this._toRemoveGeometryArray,
  47812. removedMeshes: _this._toRemoveMeshesArray
  47813. };
  47814. var message = {
  47815. payload: payload,
  47816. taskType: WorkerTaskType.UPDATE
  47817. };
  47818. var serializable = [];
  47819. for (var id in payload.updatedGeometries) {
  47820. if (payload.updatedGeometries.hasOwnProperty(id)) {
  47821. //prepare transferables
  47822. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  47823. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  47824. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  47825. }
  47826. }
  47827. _this._worker.postMessage(message, serializable);
  47828. _this._addUpdateMeshesList = {};
  47829. _this._addUpdateGeometriesList = {};
  47830. _this._toRemoveGeometryArray = [];
  47831. _this._toRemoveMeshesArray = [];
  47832. };
  47833. this._onMessageFromWorker = function (e) {
  47834. var returnData = e.data;
  47835. if (returnData.error != WorkerReplyType.SUCCESS) {
  47836. //TODO what errors can be returned from the worker?
  47837. BABYLON.Tools.Warn("error returned from worker!");
  47838. return;
  47839. }
  47840. switch (returnData.taskType) {
  47841. case WorkerTaskType.INIT:
  47842. _this._init = true;
  47843. //Update the worked with ALL of the scene's current state
  47844. _this._scene.meshes.forEach(function (mesh) {
  47845. _this.onMeshAdded(mesh);
  47846. });
  47847. _this._scene.getGeometries().forEach(function (geometry) {
  47848. _this.onGeometryAdded(geometry);
  47849. });
  47850. break;
  47851. case WorkerTaskType.UPDATE:
  47852. _this._runningUpdated--;
  47853. break;
  47854. case WorkerTaskType.COLLIDE:
  47855. var returnPayload = returnData.payload;
  47856. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47857. return;
  47858. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47859. if (callback) {
  47860. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47861. if (mesh) {
  47862. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47863. }
  47864. }
  47865. //cleanup
  47866. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47867. break;
  47868. }
  47869. };
  47870. this._collisionsCallbackArray = [];
  47871. this._init = false;
  47872. this._runningUpdated = 0;
  47873. this._addUpdateMeshesList = {};
  47874. this._addUpdateGeometriesList = {};
  47875. this._toRemoveGeometryArray = [];
  47876. this._toRemoveMeshesArray = [];
  47877. }
  47878. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47879. if (!this._init)
  47880. return;
  47881. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47882. return;
  47883. position.divideToRef(collider._radius, this._scaledPosition);
  47884. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47885. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47886. var payload = {
  47887. collider: {
  47888. position: this._scaledPosition.asArray(),
  47889. velocity: this._scaledVelocity.asArray(),
  47890. radius: collider._radius.asArray()
  47891. },
  47892. collisionId: collisionIndex,
  47893. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47894. maximumRetry: maximumRetry
  47895. };
  47896. var message = {
  47897. payload: payload,
  47898. taskType: WorkerTaskType.COLLIDE
  47899. };
  47900. this._worker.postMessage(message);
  47901. };
  47902. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47903. this._scene = scene;
  47904. this._scene.registerAfterRender(this._afterRender);
  47905. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47906. this._worker = new Worker(workerUrl);
  47907. this._worker.onmessage = this._onMessageFromWorker;
  47908. var message = {
  47909. payload: {},
  47910. taskType: WorkerTaskType.INIT
  47911. };
  47912. this._worker.postMessage(message);
  47913. };
  47914. CollisionCoordinatorWorker.prototype.destroy = function () {
  47915. this._scene.unregisterAfterRender(this._afterRender);
  47916. this._worker.terminate();
  47917. };
  47918. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47919. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47920. this.onMeshUpdated(mesh);
  47921. };
  47922. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47923. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47924. };
  47925. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47926. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47927. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47928. this.onGeometryUpdated(geometry);
  47929. };
  47930. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47931. this._toRemoveGeometryArray.push(geometry.id);
  47932. };
  47933. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47934. var submeshes = [];
  47935. if (mesh.subMeshes) {
  47936. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47937. var boundingInfo = sm.getBoundingInfo();
  47938. return {
  47939. position: idx,
  47940. verticesStart: sm.verticesStart,
  47941. verticesCount: sm.verticesCount,
  47942. indexStart: sm.indexStart,
  47943. indexCount: sm.indexCount,
  47944. hasMaterial: !!sm.getMaterial(),
  47945. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47946. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47947. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47948. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47949. };
  47950. });
  47951. }
  47952. var geometryId = null;
  47953. if (mesh instanceof BABYLON.Mesh) {
  47954. var geometry = mesh.geometry;
  47955. geometryId = geometry ? geometry.id : null;
  47956. }
  47957. else if (mesh instanceof BABYLON.InstancedMesh) {
  47958. var geometry = mesh.sourceMesh.geometry;
  47959. geometryId = geometry ? geometry.id : null;
  47960. }
  47961. var boundingInfo = mesh.getBoundingInfo();
  47962. return {
  47963. uniqueId: mesh.uniqueId,
  47964. id: mesh.id,
  47965. name: mesh.name,
  47966. geometryId: geometryId,
  47967. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47968. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47969. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47970. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47971. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47972. subMeshes: submeshes,
  47973. checkCollisions: mesh.checkCollisions
  47974. };
  47975. };
  47976. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47977. return {
  47978. id: geometry.id,
  47979. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47980. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47981. indices: new Uint32Array(geometry.getIndices() || []),
  47982. };
  47983. };
  47984. return CollisionCoordinatorWorker;
  47985. }());
  47986. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47987. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47988. function CollisionCoordinatorLegacy() {
  47989. this._scaledPosition = BABYLON.Vector3.Zero();
  47990. this._scaledVelocity = BABYLON.Vector3.Zero();
  47991. this._finalPosition = BABYLON.Vector3.Zero();
  47992. }
  47993. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47994. position.divideToRef(collider._radius, this._scaledPosition);
  47995. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47996. collider.collidedMesh = null;
  47997. collider._retry = 0;
  47998. collider._initialVelocity = this._scaledVelocity;
  47999. collider._initialPosition = this._scaledPosition;
  48000. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  48001. this._finalPosition.multiplyInPlace(collider._radius);
  48002. //run the callback
  48003. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  48004. };
  48005. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  48006. this._scene = scene;
  48007. };
  48008. CollisionCoordinatorLegacy.prototype.destroy = function () {
  48009. //Legacy need no destruction method.
  48010. };
  48011. //No update in legacy mode
  48012. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  48013. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  48014. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  48015. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  48016. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  48017. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  48018. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  48019. if (excludedMesh === void 0) { excludedMesh = null; }
  48020. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  48021. if (collider._retry >= maximumRetry) {
  48022. finalPosition.copyFrom(position);
  48023. return;
  48024. }
  48025. // Check if this is a mesh else camera or -1
  48026. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  48027. collider._initialize(position, velocity, closeDistance);
  48028. // Check all meshes
  48029. for (var index = 0; index < this._scene.meshes.length; index++) {
  48030. var mesh = this._scene.meshes[index];
  48031. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  48032. mesh._checkCollision(collider);
  48033. }
  48034. }
  48035. if (!collider.collisionFound) {
  48036. position.addToRef(velocity, finalPosition);
  48037. return;
  48038. }
  48039. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  48040. collider._getResponse(position, velocity);
  48041. }
  48042. if (velocity.length() <= closeDistance) {
  48043. finalPosition.copyFrom(position);
  48044. return;
  48045. }
  48046. collider._retry++;
  48047. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  48048. };
  48049. return CollisionCoordinatorLegacy;
  48050. }());
  48051. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  48052. })(BABYLON || (BABYLON = {}));
  48053. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  48054. var BABYLON;
  48055. (function (BABYLON) {
  48056. /**
  48057. * A particle represents one of the element emitted by a particle system.
  48058. * This is mainly define by its coordinates, direction, velocity and age.
  48059. */
  48060. var Particle = /** @class */ (function () {
  48061. /**
  48062. * Creates a new instance of @see Particle
  48063. * @param particleSystem the particle system the particle belongs to
  48064. */
  48065. function Particle(particleSystem) {
  48066. this.particleSystem = particleSystem;
  48067. /**
  48068. * The world position of the particle in the scene.
  48069. */
  48070. this.position = BABYLON.Vector3.Zero();
  48071. /**
  48072. * The world direction of the particle in the scene.
  48073. */
  48074. this.direction = BABYLON.Vector3.Zero();
  48075. /**
  48076. * The color of the particle.
  48077. */
  48078. this.color = new BABYLON.Color4(0, 0, 0, 0);
  48079. /**
  48080. * The color change of the particle per step.
  48081. */
  48082. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  48083. /**
  48084. * Defines how long will the life of the particle be.
  48085. */
  48086. this.lifeTime = 1.0;
  48087. /**
  48088. * The current age of the particle.
  48089. */
  48090. this.age = 0;
  48091. /**
  48092. * The current size of the particle.
  48093. */
  48094. this.size = 0;
  48095. /**
  48096. * The current angle of the particle.
  48097. */
  48098. this.angle = 0;
  48099. /**
  48100. * Defines how fast is the angle changing.
  48101. */
  48102. this.angularSpeed = 0;
  48103. /**
  48104. * Defines the cell index used by the particle to be rendered from a sprite.
  48105. */
  48106. this.cellIndex = 0;
  48107. this._currentFrameCounter = 0;
  48108. if (!this.particleSystem.isAnimationSheetEnabled) {
  48109. return;
  48110. }
  48111. this.cellIndex = this.particleSystem.startSpriteCellID;
  48112. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  48113. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  48114. }
  48115. else {
  48116. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  48117. }
  48118. }
  48119. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  48120. // (ageOffset / scaledUpdateSpeed) / available cells
  48121. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  48122. this._currentFrameCounter += scaledUpdateSpeed;
  48123. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  48124. this._currentFrameCounter = 0;
  48125. this.cellIndex++;
  48126. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48127. this.cellIndex = this.particleSystem.endSpriteCellID;
  48128. }
  48129. }
  48130. };
  48131. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  48132. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  48133. this.cellIndex++;
  48134. this._currentFrameCounter = 0;
  48135. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48136. if (this.particleSystem.spriteCellLoop) {
  48137. this.cellIndex = this.particleSystem.startSpriteCellID;
  48138. }
  48139. else {
  48140. this.cellIndex = this.particleSystem.endSpriteCellID;
  48141. }
  48142. }
  48143. }
  48144. else {
  48145. this._currentFrameCounter++;
  48146. }
  48147. };
  48148. /**
  48149. * Copy the properties of particle to another one.
  48150. * @param other the particle to copy the information to.
  48151. */
  48152. Particle.prototype.copyTo = function (other) {
  48153. other.position.copyFrom(this.position);
  48154. other.direction.copyFrom(this.direction);
  48155. other.color.copyFrom(this.color);
  48156. other.colorStep.copyFrom(this.colorStep);
  48157. other.lifeTime = this.lifeTime;
  48158. other.age = this.age;
  48159. other.size = this.size;
  48160. other.angle = this.angle;
  48161. other.angularSpeed = this.angularSpeed;
  48162. other.particleSystem = this.particleSystem;
  48163. other.cellIndex = this.cellIndex;
  48164. };
  48165. return Particle;
  48166. }());
  48167. BABYLON.Particle = Particle;
  48168. })(BABYLON || (BABYLON = {}));
  48169. //# sourceMappingURL=babylon.particle.js.map
  48170. var BABYLON;
  48171. (function (BABYLON) {
  48172. /**
  48173. * This represents a particle system in Babylon.
  48174. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  48175. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  48176. * @example https://doc.babylonjs.com/babylon101/particles
  48177. */
  48178. var ParticleSystem = /** @class */ (function () {
  48179. /**
  48180. * Instantiates a particle system.
  48181. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  48182. * @param name The name of the particle system
  48183. * @param capacity The max number of particles alive at the same time
  48184. * @param scene The scene the particle system belongs to
  48185. * @param customEffect a custom effect used to change the way particles are rendered by default
  48186. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  48187. * @param epsilon Offset used to render the particles
  48188. */
  48189. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  48190. if (customEffect === void 0) { customEffect = null; }
  48191. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  48192. if (epsilon === void 0) { epsilon = 0.01; }
  48193. var _this = this;
  48194. /**
  48195. * List of animations used by the particle system.
  48196. */
  48197. this.animations = [];
  48198. /**
  48199. * The rendering group used by the Particle system to chose when to render.
  48200. */
  48201. this.renderingGroupId = 0;
  48202. /**
  48203. * The emitter represents the Mesh or position we are attaching the particle system to.
  48204. */
  48205. this.emitter = null;
  48206. /**
  48207. * The density of particles, the rate of particle flow
  48208. */
  48209. this.emitRate = 10;
  48210. /**
  48211. * If you want to launch only a few particles at once, that can be done, as well.
  48212. */
  48213. this.manualEmitCount = -1;
  48214. /**
  48215. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  48216. */
  48217. this.updateSpeed = 0.01;
  48218. /**
  48219. * The amount of time the particle system is running (depends of the overall speed above).
  48220. */
  48221. this.targetStopDuration = 0;
  48222. /**
  48223. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  48224. */
  48225. this.disposeOnStop = false;
  48226. /**
  48227. * Minimum power of emitting particles.
  48228. */
  48229. this.minEmitPower = 1;
  48230. /**
  48231. * Maximum power of emitting particles.
  48232. */
  48233. this.maxEmitPower = 1;
  48234. /**
  48235. * Minimum life time of emitting particles.
  48236. */
  48237. this.minLifeTime = 1;
  48238. /**
  48239. * Maximum life time of emitting particles.
  48240. */
  48241. this.maxLifeTime = 1;
  48242. /**
  48243. * Minimum Size of emitting particles.
  48244. */
  48245. this.minSize = 1;
  48246. /**
  48247. * Maximum Size of emitting particles.
  48248. */
  48249. this.maxSize = 1;
  48250. /**
  48251. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  48252. */
  48253. this.minAngularSpeed = 0;
  48254. /**
  48255. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  48256. */
  48257. this.maxAngularSpeed = 0;
  48258. /**
  48259. * The layer mask we are rendering the particles through.
  48260. */
  48261. this.layerMask = 0x0FFFFFFF;
  48262. /**
  48263. * This can help using your own shader to render the particle system.
  48264. * The according effect will be created
  48265. */
  48266. this.customShader = null;
  48267. /**
  48268. * By default particle system starts as soon as they are created. This prevents the
  48269. * automatic start to happen and let you decide when to start emitting particles.
  48270. */
  48271. this.preventAutoStart = false;
  48272. /**
  48273. * Callback triggered when the particle animation is ending.
  48274. */
  48275. this.onAnimationEnd = null;
  48276. /**
  48277. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  48278. */
  48279. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  48280. /**
  48281. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  48282. * to override the particles.
  48283. */
  48284. this.forceDepthWrite = false;
  48285. /**
  48286. * You can use gravity if you want to give an orientation to your particles.
  48287. */
  48288. this.gravity = BABYLON.Vector3.Zero();
  48289. /**
  48290. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48291. */
  48292. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  48293. /**
  48294. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48295. */
  48296. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  48297. /**
  48298. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48299. */
  48300. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  48301. /**
  48302. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48303. */
  48304. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48305. /**
  48306. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48307. */
  48308. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48309. /**
  48310. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48311. */
  48312. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48313. /**
  48314. * Color the particle will have at the end of its lifetime.
  48315. */
  48316. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  48317. /**
  48318. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  48319. */
  48320. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48321. /**
  48322. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  48323. */
  48324. this.spriteCellLoop = true;
  48325. /**
  48326. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  48327. */
  48328. this.spriteCellChangeSpeed = 0;
  48329. /**
  48330. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  48331. */
  48332. this.startSpriteCellID = 0;
  48333. /**
  48334. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  48335. */
  48336. this.endSpriteCellID = 0;
  48337. /**
  48338. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  48339. */
  48340. this.spriteCellWidth = 0;
  48341. /**
  48342. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  48343. */
  48344. this.spriteCellHeight = 0;
  48345. /**
  48346. * An event triggered when the system is disposed.
  48347. */
  48348. this.onDisposeObservable = new BABYLON.Observable();
  48349. this._particles = new Array();
  48350. this._stockParticles = new Array();
  48351. this._newPartsExcess = 0;
  48352. this._vertexBuffers = {};
  48353. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  48354. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48355. this._scaledDirection = BABYLON.Vector3.Zero();
  48356. this._scaledGravity = BABYLON.Vector3.Zero();
  48357. this._currentRenderId = -1;
  48358. this._started = false;
  48359. this._stopped = false;
  48360. this._actualFrame = 0;
  48361. this._vertexBufferSize = 11;
  48362. this._appendParticleVertexes = null;
  48363. this.id = name;
  48364. this.name = name;
  48365. this._capacity = capacity;
  48366. this._epsilon = epsilon;
  48367. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  48368. if (isAnimationSheetEnabled) {
  48369. this._vertexBufferSize = 12;
  48370. }
  48371. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48372. this._customEffect = customEffect;
  48373. scene.particleSystems.push(this);
  48374. this._createIndexBuffer();
  48375. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  48376. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  48377. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  48378. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  48379. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  48380. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  48381. if (this._isAnimationSheetEnabled) {
  48382. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  48383. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  48384. }
  48385. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48386. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48387. this._vertexBuffers["options"] = options;
  48388. // Default behaviors
  48389. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  48390. this.updateFunction = function (particles) {
  48391. for (var index = 0; index < particles.length; index++) {
  48392. var particle = particles[index];
  48393. particle.age += _this._scaledUpdateSpeed;
  48394. if (particle.age >= particle.lifeTime) {
  48395. _this.recycleParticle(particle);
  48396. index--;
  48397. continue;
  48398. }
  48399. else {
  48400. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  48401. particle.color.addInPlace(_this._scaledColorStep);
  48402. if (particle.color.a < 0)
  48403. particle.color.a = 0;
  48404. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  48405. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  48406. particle.position.addInPlace(_this._scaledDirection);
  48407. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  48408. particle.direction.addInPlace(_this._scaledGravity);
  48409. if (_this._isAnimationSheetEnabled) {
  48410. particle.updateCellIndex(_this._scaledUpdateSpeed);
  48411. }
  48412. }
  48413. }
  48414. };
  48415. }
  48416. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  48417. /**
  48418. * Sets a callback that will be triggered when the system is disposed.
  48419. */
  48420. set: function (callback) {
  48421. if (this._onDisposeObserver) {
  48422. this.onDisposeObservable.remove(this._onDisposeObserver);
  48423. }
  48424. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48425. },
  48426. enumerable: true,
  48427. configurable: true
  48428. });
  48429. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  48430. /**
  48431. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  48432. */
  48433. get: function () {
  48434. return this._isAnimationSheetEnabled;
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. ParticleSystem.prototype._createIndexBuffer = function () {
  48440. var indices = [];
  48441. var index = 0;
  48442. for (var count = 0; count < this._capacity; count++) {
  48443. indices.push(index);
  48444. indices.push(index + 1);
  48445. indices.push(index + 2);
  48446. indices.push(index);
  48447. indices.push(index + 2);
  48448. indices.push(index + 3);
  48449. index += 4;
  48450. }
  48451. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  48452. };
  48453. /**
  48454. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  48455. * Its lifetime will start back at 0.
  48456. * @param particle The particle to recycle
  48457. */
  48458. ParticleSystem.prototype.recycleParticle = function (particle) {
  48459. var lastParticle = this._particles.pop();
  48460. if (lastParticle !== particle) {
  48461. lastParticle.copyTo(particle);
  48462. this._stockParticles.push(lastParticle);
  48463. }
  48464. };
  48465. /**
  48466. * Gets the maximum number of particles active at the same time.
  48467. * @returns The max number of active particles.
  48468. */
  48469. ParticleSystem.prototype.getCapacity = function () {
  48470. return this._capacity;
  48471. };
  48472. /**
  48473. * Gets Wether there are still active particles in the system.
  48474. * @returns True if it is alive, otherwise false.
  48475. */
  48476. ParticleSystem.prototype.isAlive = function () {
  48477. return this._alive;
  48478. };
  48479. /**
  48480. * Gets Wether the system has been started.
  48481. * @returns True if it has been started, otherwise false.
  48482. */
  48483. ParticleSystem.prototype.isStarted = function () {
  48484. return this._started;
  48485. };
  48486. /**
  48487. * Starts the particle system and begins to emit.
  48488. */
  48489. ParticleSystem.prototype.start = function () {
  48490. this._started = true;
  48491. this._stopped = false;
  48492. this._actualFrame = 0;
  48493. };
  48494. /**
  48495. * Stops the particle system.
  48496. */
  48497. ParticleSystem.prototype.stop = function () {
  48498. this._stopped = true;
  48499. };
  48500. /**
  48501. * @ignore (for internal use only)
  48502. */
  48503. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  48504. var offset = index * this._vertexBufferSize;
  48505. this._vertexData[offset] = particle.position.x;
  48506. this._vertexData[offset + 1] = particle.position.y;
  48507. this._vertexData[offset + 2] = particle.position.z;
  48508. this._vertexData[offset + 3] = particle.color.r;
  48509. this._vertexData[offset + 4] = particle.color.g;
  48510. this._vertexData[offset + 5] = particle.color.b;
  48511. this._vertexData[offset + 6] = particle.color.a;
  48512. this._vertexData[offset + 7] = particle.angle;
  48513. this._vertexData[offset + 8] = particle.size;
  48514. this._vertexData[offset + 9] = offsetX;
  48515. this._vertexData[offset + 10] = offsetY;
  48516. };
  48517. /**
  48518. * @ignore (for internal use only)
  48519. */
  48520. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48521. if (offsetX === 0)
  48522. offsetX = this._epsilon;
  48523. else if (offsetX === 1)
  48524. offsetX = 1 - this._epsilon;
  48525. if (offsetY === 0)
  48526. offsetY = this._epsilon;
  48527. else if (offsetY === 1)
  48528. offsetY = 1 - this._epsilon;
  48529. var offset = index * this._vertexBufferSize;
  48530. this._vertexData[offset] = particle.position.x;
  48531. this._vertexData[offset + 1] = particle.position.y;
  48532. this._vertexData[offset + 2] = particle.position.z;
  48533. this._vertexData[offset + 3] = particle.color.r;
  48534. this._vertexData[offset + 4] = particle.color.g;
  48535. this._vertexData[offset + 5] = particle.color.b;
  48536. this._vertexData[offset + 6] = particle.color.a;
  48537. this._vertexData[offset + 7] = particle.angle;
  48538. this._vertexData[offset + 8] = particle.size;
  48539. this._vertexData[offset + 9] = offsetX;
  48540. this._vertexData[offset + 10] = offsetY;
  48541. this._vertexData[offset + 11] = particle.cellIndex;
  48542. };
  48543. ParticleSystem.prototype._update = function (newParticles) {
  48544. // Update current
  48545. this._alive = this._particles.length > 0;
  48546. this.updateFunction(this._particles);
  48547. // Add new ones
  48548. var worldMatrix;
  48549. if (this.emitter.position) {
  48550. var emitterMesh = this.emitter;
  48551. worldMatrix = emitterMesh.getWorldMatrix();
  48552. }
  48553. else {
  48554. var emitterPosition = this.emitter;
  48555. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48556. }
  48557. var particle;
  48558. for (var index = 0; index < newParticles; index++) {
  48559. if (this._particles.length === this._capacity) {
  48560. break;
  48561. }
  48562. if (this._stockParticles.length !== 0) {
  48563. particle = this._stockParticles.pop();
  48564. particle.age = 0;
  48565. particle.cellIndex = this.startSpriteCellID;
  48566. }
  48567. else {
  48568. particle = new BABYLON.Particle(this);
  48569. }
  48570. this._particles.push(particle);
  48571. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48572. if (this.startPositionFunction) {
  48573. this.startPositionFunction(worldMatrix, particle.position, particle);
  48574. }
  48575. else {
  48576. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48577. }
  48578. if (this.startDirectionFunction) {
  48579. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48580. }
  48581. else {
  48582. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48583. }
  48584. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48585. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48586. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48587. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48588. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48589. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48590. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48591. }
  48592. };
  48593. ParticleSystem.prototype._getEffect = function () {
  48594. if (this._customEffect) {
  48595. return this._customEffect;
  48596. }
  48597. ;
  48598. var defines = [];
  48599. if (this._scene.clipPlane) {
  48600. defines.push("#define CLIPPLANE");
  48601. }
  48602. if (this._isAnimationSheetEnabled) {
  48603. defines.push("#define ANIMATESHEET");
  48604. }
  48605. // Effect
  48606. var join = defines.join("\n");
  48607. if (this._cachedDefines !== join) {
  48608. this._cachedDefines = join;
  48609. var attributesNamesOrOptions;
  48610. var effectCreationOption;
  48611. if (this._isAnimationSheetEnabled) {
  48612. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48613. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48614. }
  48615. else {
  48616. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48617. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48618. }
  48619. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48620. }
  48621. return this._effect;
  48622. };
  48623. /**
  48624. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48625. */
  48626. ParticleSystem.prototype.animate = function () {
  48627. if (!this._started)
  48628. return;
  48629. var effect = this._getEffect();
  48630. // Check
  48631. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48632. return;
  48633. if (this._currentRenderId === this._scene.getRenderId()) {
  48634. return;
  48635. }
  48636. this._currentRenderId = this._scene.getRenderId();
  48637. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48638. // determine the number of particles we need to create
  48639. var newParticles;
  48640. if (this.manualEmitCount > -1) {
  48641. newParticles = this.manualEmitCount;
  48642. this._newPartsExcess = 0;
  48643. this.manualEmitCount = 0;
  48644. }
  48645. else {
  48646. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48647. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48648. }
  48649. if (this._newPartsExcess > 1.0) {
  48650. newParticles += this._newPartsExcess >> 0;
  48651. this._newPartsExcess -= this._newPartsExcess >> 0;
  48652. }
  48653. this._alive = false;
  48654. if (!this._stopped) {
  48655. this._actualFrame += this._scaledUpdateSpeed;
  48656. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48657. this.stop();
  48658. }
  48659. else {
  48660. newParticles = 0;
  48661. }
  48662. this._update(newParticles);
  48663. // Stopped?
  48664. if (this._stopped) {
  48665. if (!this._alive) {
  48666. this._started = false;
  48667. if (this.onAnimationEnd) {
  48668. this.onAnimationEnd();
  48669. }
  48670. if (this.disposeOnStop) {
  48671. this._scene._toBeDisposed.push(this);
  48672. }
  48673. }
  48674. }
  48675. // Animation sheet
  48676. if (this._isAnimationSheetEnabled) {
  48677. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48678. }
  48679. else {
  48680. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48681. }
  48682. // Update VBO
  48683. var offset = 0;
  48684. for (var index = 0; index < this._particles.length; index++) {
  48685. var particle = this._particles[index];
  48686. this._appendParticleVertexes(offset, particle);
  48687. offset += 4;
  48688. }
  48689. if (this._vertexBuffer) {
  48690. this._vertexBuffer.update(this._vertexData);
  48691. }
  48692. };
  48693. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48694. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48695. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48696. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48697. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48698. };
  48699. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48700. this._appendParticleVertex(offset++, particle, 0, 0);
  48701. this._appendParticleVertex(offset++, particle, 1, 0);
  48702. this._appendParticleVertex(offset++, particle, 1, 1);
  48703. this._appendParticleVertex(offset++, particle, 0, 1);
  48704. };
  48705. /**
  48706. * Rebuilds the particle system.
  48707. */
  48708. ParticleSystem.prototype.rebuild = function () {
  48709. this._createIndexBuffer();
  48710. if (this._vertexBuffer) {
  48711. this._vertexBuffer._rebuild();
  48712. }
  48713. };
  48714. /**
  48715. * Renders the particle system in its current state.
  48716. * @returns the current number of particles.
  48717. */
  48718. ParticleSystem.prototype.render = function () {
  48719. var effect = this._getEffect();
  48720. // Check
  48721. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48722. return 0;
  48723. var engine = this._scene.getEngine();
  48724. // Render
  48725. engine.enableEffect(effect);
  48726. engine.setState(false);
  48727. var viewMatrix = this._scene.getViewMatrix();
  48728. effect.setTexture("diffuseSampler", this.particleTexture);
  48729. effect.setMatrix("view", viewMatrix);
  48730. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48731. if (this._isAnimationSheetEnabled) {
  48732. var baseSize = this.particleTexture.getBaseSize();
  48733. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48734. }
  48735. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48736. if (this._scene.clipPlane) {
  48737. var clipPlane = this._scene.clipPlane;
  48738. var invView = viewMatrix.clone();
  48739. invView.invert();
  48740. effect.setMatrix("invView", invView);
  48741. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48742. }
  48743. // VBOs
  48744. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48745. // Draw order
  48746. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48747. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48748. }
  48749. else {
  48750. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48751. }
  48752. if (this.forceDepthWrite) {
  48753. engine.setDepthWrite(true);
  48754. }
  48755. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48756. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48757. return this._particles.length;
  48758. };
  48759. /**
  48760. * Disposes the particle system and free the associated resources.
  48761. */
  48762. ParticleSystem.prototype.dispose = function () {
  48763. if (this._vertexBuffer) {
  48764. this._vertexBuffer.dispose();
  48765. this._vertexBuffer = null;
  48766. }
  48767. if (this._indexBuffer) {
  48768. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48769. this._indexBuffer = null;
  48770. }
  48771. if (this.particleTexture) {
  48772. this.particleTexture.dispose();
  48773. this.particleTexture = null;
  48774. }
  48775. // Remove from scene
  48776. var index = this._scene.particleSystems.indexOf(this);
  48777. if (index > -1) {
  48778. this._scene.particleSystems.splice(index, 1);
  48779. }
  48780. // Callback
  48781. this.onDisposeObservable.notifyObservers(this);
  48782. this.onDisposeObservable.clear();
  48783. };
  48784. /**
  48785. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  48786. * @param radius The radius of the sphere to emit from
  48787. * @returns the emitter
  48788. */
  48789. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  48790. if (radius === void 0) { radius = 1; }
  48791. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  48792. this.particleEmitterType = particleEmitter;
  48793. return particleEmitter;
  48794. };
  48795. /**
  48796. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  48797. * @param radius The radius of the sphere to emit from
  48798. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  48799. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  48800. * @returns the emitter
  48801. */
  48802. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  48803. if (radius === void 0) { radius = 1; }
  48804. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  48805. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  48806. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  48807. this.particleEmitterType = particleEmitter;
  48808. return particleEmitter;
  48809. };
  48810. /**
  48811. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  48812. * @param radius The radius of the cone to emit from
  48813. * @param angle The base angle of the cone
  48814. * @returns the emitter
  48815. */
  48816. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  48817. if (radius === void 0) { radius = 1; }
  48818. if (angle === void 0) { angle = Math.PI / 4; }
  48819. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  48820. this.particleEmitterType = particleEmitter;
  48821. return particleEmitter;
  48822. };
  48823. // 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.
  48824. /**
  48825. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  48826. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  48827. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48828. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48829. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48830. * @returns the emitter
  48831. */
  48832. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48833. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48834. this.direction1 = direction1;
  48835. this.direction2 = direction2;
  48836. this.minEmitBox = minEmitBox;
  48837. this.maxEmitBox = maxEmitBox;
  48838. this.particleEmitterType = particleEmitter;
  48839. return particleEmitter;
  48840. };
  48841. /**
  48842. * Clones the particle system.
  48843. * @param name The name of the cloned object
  48844. * @param newEmitter The new emitter to use
  48845. * @returns the cloned particle system
  48846. */
  48847. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48848. var custom = null;
  48849. var program = null;
  48850. if (this.customShader != null) {
  48851. program = this.customShader;
  48852. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48853. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48854. }
  48855. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48856. result.customShader = program;
  48857. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48858. if (newEmitter === undefined) {
  48859. newEmitter = this.emitter;
  48860. }
  48861. result.emitter = newEmitter;
  48862. if (this.particleTexture) {
  48863. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48864. }
  48865. if (!this.preventAutoStart) {
  48866. result.start();
  48867. }
  48868. return result;
  48869. };
  48870. /**
  48871. * Serializes the particle system to a JSON object.
  48872. * @returns the JSON object
  48873. */
  48874. ParticleSystem.prototype.serialize = function () {
  48875. var serializationObject = {};
  48876. serializationObject.name = this.name;
  48877. serializationObject.id = this.id;
  48878. // Emitter
  48879. if (this.emitter.position) {
  48880. var emitterMesh = this.emitter;
  48881. serializationObject.emitterId = emitterMesh.id;
  48882. }
  48883. else {
  48884. var emitterPosition = this.emitter;
  48885. serializationObject.emitter = emitterPosition.asArray();
  48886. }
  48887. serializationObject.capacity = this.getCapacity();
  48888. if (this.particleTexture) {
  48889. serializationObject.textureName = this.particleTexture.name;
  48890. }
  48891. // Animations
  48892. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48893. // Particle system
  48894. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48895. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48896. serializationObject.minSize = this.minSize;
  48897. serializationObject.maxSize = this.maxSize;
  48898. serializationObject.minEmitPower = this.minEmitPower;
  48899. serializationObject.maxEmitPower = this.maxEmitPower;
  48900. serializationObject.minLifeTime = this.minLifeTime;
  48901. serializationObject.maxLifeTime = this.maxLifeTime;
  48902. serializationObject.emitRate = this.emitRate;
  48903. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48904. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48905. serializationObject.gravity = this.gravity.asArray();
  48906. serializationObject.direction1 = this.direction1.asArray();
  48907. serializationObject.direction2 = this.direction2.asArray();
  48908. serializationObject.color1 = this.color1.asArray();
  48909. serializationObject.color2 = this.color2.asArray();
  48910. serializationObject.colorDead = this.colorDead.asArray();
  48911. serializationObject.updateSpeed = this.updateSpeed;
  48912. serializationObject.targetStopDuration = this.targetStopDuration;
  48913. serializationObject.textureMask = this.textureMask.asArray();
  48914. serializationObject.blendMode = this.blendMode;
  48915. serializationObject.customShader = this.customShader;
  48916. serializationObject.preventAutoStart = this.preventAutoStart;
  48917. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48918. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48919. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48920. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48921. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48922. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48923. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48924. return serializationObject;
  48925. };
  48926. /**
  48927. * Parses a JSON object to create a particle system.
  48928. * @param parsedParticleSystem The JSON object to parse
  48929. * @param scene The scene to create the particle system in
  48930. * @param rootUrl The root url to use to load external dependencies like texture
  48931. * @returns the Parsed particle system
  48932. */
  48933. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48934. var name = parsedParticleSystem.name;
  48935. var custom = null;
  48936. var program = null;
  48937. if (parsedParticleSystem.customShader) {
  48938. program = parsedParticleSystem.customShader;
  48939. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48940. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48941. }
  48942. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48943. particleSystem.customShader = program;
  48944. if (parsedParticleSystem.id) {
  48945. particleSystem.id = parsedParticleSystem.id;
  48946. }
  48947. // Auto start
  48948. if (parsedParticleSystem.preventAutoStart) {
  48949. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48950. }
  48951. // Texture
  48952. if (parsedParticleSystem.textureName) {
  48953. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48954. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48955. }
  48956. // Emitter
  48957. if (parsedParticleSystem.emitterId) {
  48958. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48959. }
  48960. else {
  48961. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48962. }
  48963. // Animations
  48964. if (parsedParticleSystem.animations) {
  48965. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48966. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48967. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48968. }
  48969. }
  48970. if (parsedParticleSystem.autoAnimate) {
  48971. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48972. }
  48973. // Particle system
  48974. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48975. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48976. particleSystem.minSize = parsedParticleSystem.minSize;
  48977. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48978. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48979. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48980. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48981. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48982. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48983. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48984. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48985. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48986. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48987. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48988. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48989. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48990. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48991. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48992. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48993. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48994. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48995. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48996. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48997. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48998. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48999. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  49000. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  49001. if (!particleSystem.preventAutoStart) {
  49002. particleSystem.start();
  49003. }
  49004. return particleSystem;
  49005. };
  49006. /**
  49007. * Source color is added to the destination color without alpha affecting the result.
  49008. */
  49009. ParticleSystem.BLENDMODE_ONEONE = 0;
  49010. /**
  49011. * Blend current color and particle color using particle’s alpha.
  49012. */
  49013. ParticleSystem.BLENDMODE_STANDARD = 1;
  49014. return ParticleSystem;
  49015. }());
  49016. BABYLON.ParticleSystem = ParticleSystem;
  49017. })(BABYLON || (BABYLON = {}));
  49018. //# sourceMappingURL=babylon.particleSystem.js.map
  49019. var BABYLON;
  49020. (function (BABYLON) {
  49021. /**
  49022. * Particle emitter emitting particles from the inside of a box.
  49023. * It emits the particles randomly between 2 given directions.
  49024. */
  49025. var BoxParticleEmitter = /** @class */ (function () {
  49026. // to be updated like the rest of emitters when breaking changes.
  49027. // all property should be come public variables and passed through constructor.
  49028. /**
  49029. * Creates a new instance of @see BoxParticleEmitter
  49030. * @param _particleSystem the particle system associated with the emitter
  49031. */
  49032. function BoxParticleEmitter(_particleSystem) {
  49033. this._particleSystem = _particleSystem;
  49034. }
  49035. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  49036. /**
  49037. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49038. */
  49039. get: function () {
  49040. return this._particleSystem.direction1;
  49041. },
  49042. /**
  49043. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49044. */
  49045. set: function (value) {
  49046. this._particleSystem.direction1 = value;
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  49052. /**
  49053. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49054. */
  49055. get: function () {
  49056. return this._particleSystem.direction2;
  49057. },
  49058. /**
  49059. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49060. */
  49061. set: function (value) {
  49062. this._particleSystem.direction2 = value;
  49063. },
  49064. enumerable: true,
  49065. configurable: true
  49066. });
  49067. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  49068. /**
  49069. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49070. */
  49071. get: function () {
  49072. return this._particleSystem.minEmitBox;
  49073. },
  49074. /**
  49075. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49076. */
  49077. set: function (value) {
  49078. this._particleSystem.minEmitBox = value;
  49079. },
  49080. enumerable: true,
  49081. configurable: true
  49082. });
  49083. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  49084. /**
  49085. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49086. */
  49087. get: function () {
  49088. return this._particleSystem.maxEmitBox;
  49089. },
  49090. /**
  49091. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49092. */
  49093. set: function (value) {
  49094. this._particleSystem.maxEmitBox = value;
  49095. },
  49096. enumerable: true,
  49097. configurable: true
  49098. });
  49099. /**
  49100. * Called by the particle System when the direction is computed for the created particle.
  49101. * @param emitPower is the power of the particle (speed)
  49102. * @param worldMatrix is the world matrix of the particle system
  49103. * @param directionToUpdate is the direction vector to update with the result
  49104. * @param particle is the particle we are computed the direction for
  49105. */
  49106. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49107. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49108. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49109. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49110. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49111. };
  49112. /**
  49113. * Called by the particle System when the position is computed for the created particle.
  49114. * @param worldMatrix is the world matrix of the particle system
  49115. * @param positionToUpdate is the position vector to update with the result
  49116. * @param particle is the particle we are computed the position for
  49117. */
  49118. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49119. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  49120. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  49121. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  49122. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49123. };
  49124. /**
  49125. * Clones the current emitter and returns a copy of it
  49126. * @returns the new emitter
  49127. */
  49128. BoxParticleEmitter.prototype.clone = function () {
  49129. var newOne = new BoxParticleEmitter(this._particleSystem);
  49130. BABYLON.Tools.DeepCopy(this, newOne);
  49131. return newOne;
  49132. };
  49133. return BoxParticleEmitter;
  49134. }());
  49135. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  49136. })(BABYLON || (BABYLON = {}));
  49137. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  49138. var BABYLON;
  49139. (function (BABYLON) {
  49140. /**
  49141. * Particle emitter emitting particles from the inside of a cone.
  49142. * It emits the particles alongside the cone volume from the base to the particle.
  49143. * The emission direction might be randomized.
  49144. */
  49145. var ConeParticleEmitter = /** @class */ (function () {
  49146. /**
  49147. * Creates a new instance of @see ConeParticleEmitter
  49148. * @param radius the radius of the emission cone
  49149. * @param angles the cone base angle
  49150. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49151. */
  49152. function ConeParticleEmitter(radius,
  49153. /**
  49154. * The radius of the emission cone.
  49155. */
  49156. angle,
  49157. /**
  49158. * The cone base angle.
  49159. */
  49160. directionRandomizer) {
  49161. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49162. this.angle = angle;
  49163. this.directionRandomizer = directionRandomizer;
  49164. this.radius = radius;
  49165. }
  49166. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  49167. /**
  49168. * Gets the radius of the emission cone.
  49169. */
  49170. get: function () {
  49171. return this._radius;
  49172. },
  49173. /**
  49174. * Sets the radius of the emission cone.
  49175. */
  49176. set: function (value) {
  49177. this._radius = value;
  49178. if (this.angle !== 0) {
  49179. this._height = value / Math.tan(this.angle / 2);
  49180. }
  49181. else {
  49182. this._height = 1;
  49183. }
  49184. },
  49185. enumerable: true,
  49186. configurable: true
  49187. });
  49188. /**
  49189. * Called by the particle System when the direction is computed for the created particle.
  49190. * @param emitPower is the power of the particle (speed)
  49191. * @param worldMatrix is the world matrix of the particle system
  49192. * @param directionToUpdate is the direction vector to update with the result
  49193. * @param particle is the particle we are computed the direction for
  49194. */
  49195. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49196. if (this.angle === 0) {
  49197. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  49198. }
  49199. else {
  49200. // measure the direction Vector from the emitter to the particle.
  49201. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49202. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49203. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49204. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49205. direction.x += randX;
  49206. direction.y += randY;
  49207. direction.z += randZ;
  49208. direction.normalize();
  49209. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49210. }
  49211. };
  49212. /**
  49213. * Called by the particle System when the position is computed for the created particle.
  49214. * @param worldMatrix is the world matrix of the particle system
  49215. * @param positionToUpdate is the position vector to update with the result
  49216. * @param particle is the particle we are computed the position for
  49217. */
  49218. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49219. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  49220. var h = BABYLON.Scalar.RandomRange(0, 1);
  49221. // Better distribution in a cone at normal angles.
  49222. h = 1 - h * h;
  49223. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  49224. radius = radius * h / this._height;
  49225. var randX = radius * Math.sin(s);
  49226. var randZ = radius * Math.cos(s);
  49227. var randY = h;
  49228. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49229. };
  49230. /**
  49231. * Clones the current emitter and returns a copy of it
  49232. * @returns the new emitter
  49233. */
  49234. ConeParticleEmitter.prototype.clone = function () {
  49235. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  49236. BABYLON.Tools.DeepCopy(this, newOne);
  49237. return newOne;
  49238. };
  49239. return ConeParticleEmitter;
  49240. }());
  49241. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  49242. })(BABYLON || (BABYLON = {}));
  49243. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  49244. var BABYLON;
  49245. (function (BABYLON) {
  49246. /**
  49247. * Particle emitter emitting particles from the inside of a sphere.
  49248. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  49249. */
  49250. var SphereParticleEmitter = /** @class */ (function () {
  49251. /**
  49252. * Creates a new instance of @see SphereParticleEmitter
  49253. * @param radius the radius of the emission sphere
  49254. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49255. */
  49256. function SphereParticleEmitter(
  49257. /**
  49258. * The radius of the emission sphere.
  49259. */
  49260. radius,
  49261. /**
  49262. * How much to randomize the particle direction [0-1].
  49263. */
  49264. directionRandomizer) {
  49265. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49266. this.radius = radius;
  49267. this.directionRandomizer = directionRandomizer;
  49268. }
  49269. /**
  49270. * Called by the particle System when the direction is computed for the created particle.
  49271. * @param emitPower is the power of the particle (speed)
  49272. * @param worldMatrix is the world matrix of the particle system
  49273. * @param directionToUpdate is the direction vector to update with the result
  49274. * @param particle is the particle we are computed the direction for
  49275. */
  49276. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49277. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49278. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49279. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49280. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49281. direction.x += randX;
  49282. direction.y += randY;
  49283. direction.z += randZ;
  49284. direction.normalize();
  49285. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49286. };
  49287. /**
  49288. * Called by the particle System when the position is computed for the created particle.
  49289. * @param worldMatrix is the world matrix of the particle system
  49290. * @param positionToUpdate is the position vector to update with the result
  49291. * @param particle is the particle we are computed the position for
  49292. */
  49293. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49294. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  49295. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  49296. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  49297. var randY = this.radius * Math.cos(theta);
  49298. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  49299. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49300. };
  49301. /**
  49302. * Clones the current emitter and returns a copy of it
  49303. * @returns the new emitter
  49304. */
  49305. SphereParticleEmitter.prototype.clone = function () {
  49306. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  49307. BABYLON.Tools.DeepCopy(this, newOne);
  49308. return newOne;
  49309. };
  49310. return SphereParticleEmitter;
  49311. }());
  49312. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  49313. /**
  49314. * Particle emitter emitting particles from the inside of a sphere.
  49315. * It emits the particles randomly between two vectors.
  49316. */
  49317. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  49318. __extends(SphereDirectedParticleEmitter, _super);
  49319. /**
  49320. * Creates a new instance of @see SphereDirectedParticleEmitter
  49321. * @param radius the radius of the emission sphere
  49322. * @param direction1 the min limit of the emission direction
  49323. * @param direction2 the max limit of the emission direction
  49324. */
  49325. function SphereDirectedParticleEmitter(radius,
  49326. /**
  49327. * The min limit of the emission direction.
  49328. */
  49329. direction1,
  49330. /**
  49331. * The max limit of the emission direction.
  49332. */
  49333. direction2) {
  49334. var _this = _super.call(this, radius) || this;
  49335. _this.direction1 = direction1;
  49336. _this.direction2 = direction2;
  49337. return _this;
  49338. }
  49339. /**
  49340. * Called by the particle System when the direction is computed for the created particle.
  49341. * @param emitPower is the power of the particle (speed)
  49342. * @param worldMatrix is the world matrix of the particle system
  49343. * @param directionToUpdate is the direction vector to update with the result
  49344. * @param particle is the particle we are computed the direction for
  49345. */
  49346. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49347. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49348. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49349. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49350. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49351. };
  49352. /**
  49353. * Clones the current emitter and returns a copy of it
  49354. * @returns the new emitter
  49355. */
  49356. SphereDirectedParticleEmitter.prototype.clone = function () {
  49357. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  49358. BABYLON.Tools.DeepCopy(this, newOne);
  49359. return newOne;
  49360. };
  49361. return SphereDirectedParticleEmitter;
  49362. }(SphereParticleEmitter));
  49363. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  49364. })(BABYLON || (BABYLON = {}));
  49365. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  49366. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  49367. var BABYLON;
  49368. (function (BABYLON) {
  49369. /**
  49370. * Represents one particle of a solid particle system.
  49371. * @see SolidParticleSystem
  49372. */
  49373. var SolidParticle = /** @class */ (function () {
  49374. /**
  49375. * Creates a Solid Particle object.
  49376. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49377. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49378. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49379. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49380. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49381. * @param shapeId (integer) is the model shape identifier in the SPS.
  49382. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49383. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49384. */
  49385. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49386. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49387. /**
  49388. * particle global index
  49389. */
  49390. this.idx = 0;
  49391. /**
  49392. * The color of the particle
  49393. */
  49394. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49395. /**
  49396. * The world space position of the particle.
  49397. */
  49398. this.position = BABYLON.Vector3.Zero();
  49399. /**
  49400. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49401. */
  49402. this.rotation = BABYLON.Vector3.Zero();
  49403. /**
  49404. * The scaling of the particle.
  49405. */
  49406. this.scaling = BABYLON.Vector3.One();
  49407. /**
  49408. * The uvs of the particle.
  49409. */
  49410. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49411. /**
  49412. * The current speed of the particle.
  49413. */
  49414. this.velocity = BABYLON.Vector3.Zero();
  49415. /**
  49416. * The pivot point in the particle local space.
  49417. */
  49418. this.pivot = BABYLON.Vector3.Zero();
  49419. /**
  49420. * Is the particle active or not ?
  49421. */
  49422. this.alive = true;
  49423. /**
  49424. * Is the particle visible or not ?
  49425. */
  49426. this.isVisible = true;
  49427. /**
  49428. * Index of this particle in the global "positions" array (Internal use)
  49429. */
  49430. this._pos = 0;
  49431. /**
  49432. * Index of this particle in the global "indices" array (Internal use)
  49433. */
  49434. this._ind = 0;
  49435. /**
  49436. * ModelShape id of this particle
  49437. */
  49438. this.shapeId = 0;
  49439. /**
  49440. * Index of the particle in its shape id (Internal use)
  49441. */
  49442. this.idxInShape = 0;
  49443. /**
  49444. * Still set as invisible in order to skip useless computations (Internal use)
  49445. */
  49446. this._stillInvisible = false;
  49447. /**
  49448. * Last computed particle rotation matrix
  49449. */
  49450. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  49451. this.idx = particleIndex;
  49452. this._pos = positionIndex;
  49453. this._ind = indiceIndex;
  49454. this._model = model;
  49455. this.shapeId = shapeId;
  49456. this.idxInShape = idxInShape;
  49457. this._sps = sps;
  49458. if (modelBoundingInfo) {
  49459. this._modelBoundingInfo = modelBoundingInfo;
  49460. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49461. }
  49462. }
  49463. Object.defineProperty(SolidParticle.prototype, "scale", {
  49464. /**
  49465. * Legacy support, changed scale to scaling
  49466. */
  49467. get: function () {
  49468. return this.scaling;
  49469. },
  49470. /**
  49471. * Legacy support, changed scale to scaling
  49472. */
  49473. set: function (scale) {
  49474. this.scaling = scale;
  49475. },
  49476. enumerable: true,
  49477. configurable: true
  49478. });
  49479. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49480. /**
  49481. * Legacy support, changed quaternion to rotationQuaternion
  49482. */
  49483. get: function () {
  49484. return this.rotationQuaternion;
  49485. },
  49486. /**
  49487. * Legacy support, changed quaternion to rotationQuaternion
  49488. */
  49489. set: function (q) {
  49490. this.rotationQuaternion = q;
  49491. },
  49492. enumerable: true,
  49493. configurable: true
  49494. });
  49495. /**
  49496. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49497. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49498. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49499. * @returns true if it intersects
  49500. */
  49501. SolidParticle.prototype.intersectsMesh = function (target) {
  49502. if (!this._boundingInfo || !target._boundingInfo) {
  49503. return false;
  49504. }
  49505. if (this._sps._bSphereOnly) {
  49506. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49507. }
  49508. return this._boundingInfo.intersects(target._boundingInfo, false);
  49509. };
  49510. return SolidParticle;
  49511. }());
  49512. BABYLON.SolidParticle = SolidParticle;
  49513. /**
  49514. * Represents the shape of the model used by one particle of a solid particle system.
  49515. * SPS internal tool, don't use it manually.
  49516. * @see SolidParticleSystem
  49517. */
  49518. var ModelShape = /** @class */ (function () {
  49519. /**
  49520. * 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.
  49521. * SPS internal tool, don't use it manually.
  49522. * @ignore
  49523. */
  49524. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49525. /**
  49526. * length of the shape in the model indices array (internal use)
  49527. */
  49528. this._indicesLength = 0;
  49529. this.shapeID = id;
  49530. this._shape = shape;
  49531. this._indicesLength = indicesLength;
  49532. this._shapeUV = shapeUV;
  49533. this._positionFunction = posFunction;
  49534. this._vertexFunction = vtxFunction;
  49535. }
  49536. return ModelShape;
  49537. }());
  49538. BABYLON.ModelShape = ModelShape;
  49539. /**
  49540. * Represents a Depth Sorted Particle in the solid particle system.
  49541. * @see SolidParticleSystem
  49542. */
  49543. var DepthSortedParticle = /** @class */ (function () {
  49544. function DepthSortedParticle() {
  49545. /**
  49546. * Index of the particle in the "indices" array
  49547. */
  49548. this.ind = 0;
  49549. /**
  49550. * Length of the particle shape in the "indices" array
  49551. */
  49552. this.indicesLength = 0;
  49553. /**
  49554. * Squared distance from the particle to the camera
  49555. */
  49556. this.sqDistance = 0.0;
  49557. }
  49558. return DepthSortedParticle;
  49559. }());
  49560. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49561. })(BABYLON || (BABYLON = {}));
  49562. //# sourceMappingURL=babylon.solidParticle.js.map
  49563. var BABYLON;
  49564. (function (BABYLON) {
  49565. /**
  49566. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49567. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  49568. * The SPS is also a particle system. It provides some methods to manage the particles.
  49569. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49570. *
  49571. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49572. */
  49573. var SolidParticleSystem = /** @class */ (function () {
  49574. /**
  49575. * Creates a SPS (Solid Particle System) object.
  49576. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49577. * @param scene (Scene) is the scene in which the SPS is added.
  49578. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49579. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49580. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49581. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49582. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49583. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49584. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49585. */
  49586. function SolidParticleSystem(name, scene, options) {
  49587. /**
  49588. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49589. * Example : var p = SPS.particles[i];
  49590. */
  49591. this.particles = new Array();
  49592. /**
  49593. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49594. */
  49595. this.nbParticles = 0;
  49596. /**
  49597. * If the particles must ever face the camera (default false). Useful for planar particles.
  49598. */
  49599. this.billboard = false;
  49600. /**
  49601. * Recompute normals when adding a shape
  49602. */
  49603. this.recomputeNormals = true;
  49604. /**
  49605. * This a counter ofr your own usage. It's not set by any SPS functions.
  49606. */
  49607. this.counter = 0;
  49608. /**
  49609. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49610. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49611. */
  49612. this.vars = {};
  49613. /**
  49614. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49615. */
  49616. this._bSphereOnly = false;
  49617. /**
  49618. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49619. */
  49620. this._bSphereRadiusFactor = 1.0;
  49621. this._positions = new Array();
  49622. this._indices = new Array();
  49623. this._normals = new Array();
  49624. this._colors = new Array();
  49625. this._uvs = new Array();
  49626. this._index = 0; // indices index
  49627. this._updatable = true;
  49628. this._pickable = false;
  49629. this._isVisibilityBoxLocked = false;
  49630. this._alwaysVisible = false;
  49631. this._depthSort = false;
  49632. this._shapeCounter = 0;
  49633. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49634. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49635. this._computeParticleColor = true;
  49636. this._computeParticleTexture = true;
  49637. this._computeParticleRotation = true;
  49638. this._computeParticleVertex = false;
  49639. this._computeBoundingBox = false;
  49640. this._depthSortParticles = true;
  49641. this._cam_axisZ = BABYLON.Vector3.Zero();
  49642. this._cam_axisY = BABYLON.Vector3.Zero();
  49643. this._cam_axisX = BABYLON.Vector3.Zero();
  49644. this._axisZ = BABYLON.Axis.Z;
  49645. this._camDir = BABYLON.Vector3.Zero();
  49646. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49647. this._rotMatrix = new BABYLON.Matrix();
  49648. this._invertMatrix = new BABYLON.Matrix();
  49649. this._rotated = BABYLON.Vector3.Zero();
  49650. this._quaternion = new BABYLON.Quaternion();
  49651. this._vertex = BABYLON.Vector3.Zero();
  49652. this._normal = BABYLON.Vector3.Zero();
  49653. this._yaw = 0.0;
  49654. this._pitch = 0.0;
  49655. this._roll = 0.0;
  49656. this._halfroll = 0.0;
  49657. this._halfpitch = 0.0;
  49658. this._halfyaw = 0.0;
  49659. this._sinRoll = 0.0;
  49660. this._cosRoll = 0.0;
  49661. this._sinPitch = 0.0;
  49662. this._cosPitch = 0.0;
  49663. this._sinYaw = 0.0;
  49664. this._cosYaw = 0.0;
  49665. this._mustUnrotateFixedNormals = false;
  49666. this._minimum = BABYLON.Tmp.Vector3[0];
  49667. this._maximum = BABYLON.Tmp.Vector3[1];
  49668. this._minBbox = BABYLON.Tmp.Vector3[4];
  49669. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49670. this._particlesIntersect = false;
  49671. this._depthSortFunction = function (p1, p2) {
  49672. return (p2.sqDistance - p1.sqDistance);
  49673. };
  49674. this._needs32Bits = false;
  49675. this.name = name;
  49676. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49677. this._camera = scene.activeCamera;
  49678. this._pickable = options ? options.isPickable : false;
  49679. this._depthSort = options ? options.enableDepthSort : false;
  49680. this._particlesIntersect = options ? options.particleIntersection : false;
  49681. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49682. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49683. if (options && options.updatable) {
  49684. this._updatable = options.updatable;
  49685. }
  49686. else {
  49687. this._updatable = true;
  49688. }
  49689. if (this._pickable) {
  49690. this.pickedParticles = [];
  49691. }
  49692. if (this._depthSort) {
  49693. this.depthSortedParticles = [];
  49694. }
  49695. }
  49696. /**
  49697. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49698. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49699. * @returns the created mesh
  49700. */
  49701. SolidParticleSystem.prototype.buildMesh = function () {
  49702. if (this.nbParticles === 0) {
  49703. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49704. this.addShape(triangle, 1);
  49705. triangle.dispose();
  49706. }
  49707. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49708. this._positions32 = new Float32Array(this._positions);
  49709. this._uvs32 = new Float32Array(this._uvs);
  49710. this._colors32 = new Float32Array(this._colors);
  49711. if (this.recomputeNormals) {
  49712. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49713. }
  49714. this._normals32 = new Float32Array(this._normals);
  49715. this._fixedNormal32 = new Float32Array(this._normals);
  49716. if (this._mustUnrotateFixedNormals) {
  49717. this._unrotateFixedNormals();
  49718. }
  49719. var vertexData = new BABYLON.VertexData();
  49720. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49721. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49722. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49723. if (this._uvs32) {
  49724. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49725. ;
  49726. }
  49727. if (this._colors32) {
  49728. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49729. }
  49730. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49731. vertexData.applyToMesh(mesh, this._updatable);
  49732. this.mesh = mesh;
  49733. this.mesh.isPickable = this._pickable;
  49734. // free memory
  49735. if (!this._depthSort) {
  49736. this._indices = null;
  49737. }
  49738. this._positions = null;
  49739. this._normals = null;
  49740. this._uvs = null;
  49741. this._colors = null;
  49742. if (!this._updatable) {
  49743. this.particles.length = 0;
  49744. }
  49745. return mesh;
  49746. };
  49747. /**
  49748. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49749. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49750. * Thus the particles generated from `digest()` have their property `position` set yet.
  49751. * @param mesh ( Mesh ) is the mesh to be digested
  49752. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49753. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49754. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49755. * @returns the current SPS
  49756. */
  49757. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49758. var size = (options && options.facetNb) || 1;
  49759. var number = (options && options.number) || 0;
  49760. var delta = (options && options.delta) || 0;
  49761. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49762. var meshInd = mesh.getIndices();
  49763. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49764. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49765. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49766. var f = 0; // facet counter
  49767. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49768. // compute size from number
  49769. if (number) {
  49770. number = (number > totalFacets) ? totalFacets : number;
  49771. size = Math.round(totalFacets / number);
  49772. delta = 0;
  49773. }
  49774. else {
  49775. size = (size > totalFacets) ? totalFacets : size;
  49776. }
  49777. var facetPos = []; // submesh positions
  49778. var facetInd = []; // submesh indices
  49779. var facetUV = []; // submesh UV
  49780. var facetCol = []; // submesh colors
  49781. var barycenter = BABYLON.Tmp.Vector3[0];
  49782. var sizeO = size;
  49783. while (f < totalFacets) {
  49784. size = sizeO + Math.floor((1 + delta) * Math.random());
  49785. if (f > totalFacets - size) {
  49786. size = totalFacets - f;
  49787. }
  49788. // reset temp arrays
  49789. facetPos.length = 0;
  49790. facetInd.length = 0;
  49791. facetUV.length = 0;
  49792. facetCol.length = 0;
  49793. // iterate over "size" facets
  49794. var fi = 0;
  49795. for (var j = f * 3; j < (f + size) * 3; j++) {
  49796. facetInd.push(fi);
  49797. var i = meshInd[j];
  49798. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49799. if (meshUV) {
  49800. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49801. }
  49802. if (meshCol) {
  49803. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49804. }
  49805. fi++;
  49806. }
  49807. // create a model shape for each single particle
  49808. var idx = this.nbParticles;
  49809. var shape = this._posToShape(facetPos);
  49810. var shapeUV = this._uvsToShapeUV(facetUV);
  49811. // compute the barycenter of the shape
  49812. var v;
  49813. for (v = 0; v < shape.length; v++) {
  49814. barycenter.addInPlace(shape[v]);
  49815. }
  49816. barycenter.scaleInPlace(1 / shape.length);
  49817. // shift the shape from its barycenter to the origin
  49818. for (v = 0; v < shape.length; v++) {
  49819. shape[v].subtractInPlace(barycenter);
  49820. }
  49821. var bInfo;
  49822. if (this._particlesIntersect) {
  49823. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49824. }
  49825. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  49826. // add the particle in the SPS
  49827. var currentPos = this._positions.length;
  49828. var currentInd = this._indices.length;
  49829. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49830. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  49831. // initialize the particle position
  49832. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49833. this._index += shape.length;
  49834. idx++;
  49835. this.nbParticles++;
  49836. this._shapeCounter++;
  49837. f += size;
  49838. }
  49839. return this;
  49840. };
  49841. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  49842. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  49843. var index = 0;
  49844. var idx = 0;
  49845. for (var p = 0; p < this.particles.length; p++) {
  49846. this._particle = this.particles[p];
  49847. this._shape = this._particle._model._shape;
  49848. if (this._particle.rotationQuaternion) {
  49849. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49850. }
  49851. else {
  49852. this._yaw = this._particle.rotation.y;
  49853. this._pitch = this._particle.rotation.x;
  49854. this._roll = this._particle.rotation.z;
  49855. this._quaternionRotationYPR();
  49856. }
  49857. this._quaternionToRotationMatrix();
  49858. this._rotMatrix.invertToRef(this._invertMatrix);
  49859. for (var pt = 0; pt < this._shape.length; pt++) {
  49860. idx = index + pt * 3;
  49861. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  49862. this._fixedNormal32[idx] = this._normal.x;
  49863. this._fixedNormal32[idx + 1] = this._normal.y;
  49864. this._fixedNormal32[idx + 2] = this._normal.z;
  49865. }
  49866. index = idx + 3;
  49867. }
  49868. };
  49869. //reset copy
  49870. SolidParticleSystem.prototype._resetCopy = function () {
  49871. this._copy.position.x = 0;
  49872. this._copy.position.y = 0;
  49873. this._copy.position.z = 0;
  49874. this._copy.rotation.x = 0;
  49875. this._copy.rotation.y = 0;
  49876. this._copy.rotation.z = 0;
  49877. this._copy.rotationQuaternion = null;
  49878. this._copy.scaling.x = 1.0;
  49879. this._copy.scaling.y = 1.0;
  49880. this._copy.scaling.z = 1.0;
  49881. this._copy.uvs.x = 0;
  49882. this._copy.uvs.y = 0;
  49883. this._copy.uvs.z = 1.0;
  49884. this._copy.uvs.w = 1.0;
  49885. this._copy.color = null;
  49886. };
  49887. // _meshBuilder : inserts the shape model in the global SPS mesh
  49888. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49889. var i;
  49890. var u = 0;
  49891. var c = 0;
  49892. var n = 0;
  49893. this._resetCopy();
  49894. if (options && options.positionFunction) {
  49895. options.positionFunction(this._copy, idx, idxInShape);
  49896. this._mustUnrotateFixedNormals = true;
  49897. }
  49898. if (this._copy.rotationQuaternion) {
  49899. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49900. }
  49901. else {
  49902. this._yaw = this._copy.rotation.y;
  49903. this._pitch = this._copy.rotation.x;
  49904. this._roll = this._copy.rotation.z;
  49905. this._quaternionRotationYPR();
  49906. }
  49907. this._quaternionToRotationMatrix();
  49908. for (i = 0; i < shape.length; i++) {
  49909. this._vertex.x = shape[i].x;
  49910. this._vertex.y = shape[i].y;
  49911. this._vertex.z = shape[i].z;
  49912. if (options && options.vertexFunction) {
  49913. options.vertexFunction(this._copy, this._vertex, i);
  49914. }
  49915. this._vertex.x *= this._copy.scaling.x;
  49916. this._vertex.y *= this._copy.scaling.y;
  49917. this._vertex.z *= this._copy.scaling.z;
  49918. this._vertex.x += this._copy.pivot.x;
  49919. this._vertex.y += this._copy.pivot.y;
  49920. this._vertex.z += this._copy.pivot.z;
  49921. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49922. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49923. if (meshUV) {
  49924. 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);
  49925. u += 2;
  49926. }
  49927. if (this._copy.color) {
  49928. this._color = this._copy.color;
  49929. }
  49930. else if (meshCol && meshCol[c] !== undefined) {
  49931. this._color.r = meshCol[c];
  49932. this._color.g = meshCol[c + 1];
  49933. this._color.b = meshCol[c + 2];
  49934. this._color.a = meshCol[c + 3];
  49935. }
  49936. else {
  49937. this._color.r = 1.0;
  49938. this._color.g = 1.0;
  49939. this._color.b = 1.0;
  49940. this._color.a = 1.0;
  49941. }
  49942. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49943. c += 4;
  49944. if (!this.recomputeNormals && meshNor) {
  49945. this._normal.x = meshNor[n];
  49946. this._normal.y = meshNor[n + 1];
  49947. this._normal.z = meshNor[n + 2];
  49948. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49949. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49950. n += 3;
  49951. }
  49952. }
  49953. for (i = 0; i < meshInd.length; i++) {
  49954. var current_ind = p + meshInd[i];
  49955. indices.push(current_ind);
  49956. if (current_ind > 65535) {
  49957. this._needs32Bits = true;
  49958. }
  49959. }
  49960. if (this._pickable) {
  49961. var nbfaces = meshInd.length / 3;
  49962. for (i = 0; i < nbfaces; i++) {
  49963. this.pickedParticles.push({ idx: idx, faceId: i });
  49964. }
  49965. }
  49966. if (this._depthSort) {
  49967. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49968. }
  49969. return this._copy;
  49970. };
  49971. // returns a shape array from positions array
  49972. SolidParticleSystem.prototype._posToShape = function (positions) {
  49973. var shape = [];
  49974. for (var i = 0; i < positions.length; i += 3) {
  49975. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49976. }
  49977. return shape;
  49978. };
  49979. // returns a shapeUV array from a Vector4 uvs
  49980. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49981. var shapeUV = [];
  49982. if (uvs) {
  49983. for (var i = 0; i < uvs.length; i++)
  49984. shapeUV.push(uvs[i]);
  49985. }
  49986. return shapeUV;
  49987. };
  49988. // adds a new particle object in the particles array
  49989. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49990. if (bInfo === void 0) { bInfo = null; }
  49991. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49992. this.particles.push(sp);
  49993. return sp;
  49994. };
  49995. /**
  49996. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49997. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49998. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49999. * @param nb (positive integer) the number of particles to be created from this model
  50000. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  50001. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  50002. * @returns the number of shapes in the system
  50003. */
  50004. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50005. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50006. var meshInd = mesh.getIndices();
  50007. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50008. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50009. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50010. var bbInfo;
  50011. if (this._particlesIntersect) {
  50012. bbInfo = mesh.getBoundingInfo();
  50013. }
  50014. var shape = this._posToShape(meshPos);
  50015. var shapeUV = this._uvsToShapeUV(meshUV);
  50016. var posfunc = options ? options.positionFunction : null;
  50017. var vtxfunc = options ? options.vertexFunction : null;
  50018. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  50019. // particles
  50020. var sp;
  50021. var currentCopy;
  50022. var idx = this.nbParticles;
  50023. for (var i = 0; i < nb; i++) {
  50024. var currentPos = this._positions.length;
  50025. var currentInd = this._indices.length;
  50026. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50027. if (this._updatable) {
  50028. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  50029. sp.position.copyFrom(currentCopy.position);
  50030. sp.rotation.copyFrom(currentCopy.rotation);
  50031. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  50032. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  50033. }
  50034. if (currentCopy.color && sp.color) {
  50035. sp.color.copyFrom(currentCopy.color);
  50036. }
  50037. sp.scaling.copyFrom(currentCopy.scaling);
  50038. sp.uvs.copyFrom(currentCopy.uvs);
  50039. }
  50040. this._index += shape.length;
  50041. idx++;
  50042. }
  50043. this.nbParticles += nb;
  50044. this._shapeCounter++;
  50045. return this._shapeCounter - 1;
  50046. };
  50047. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50048. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50049. this._resetCopy();
  50050. if (particle._model._positionFunction) {
  50051. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50052. }
  50053. if (this._copy.rotationQuaternion) {
  50054. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50055. }
  50056. else {
  50057. this._yaw = this._copy.rotation.y;
  50058. this._pitch = this._copy.rotation.x;
  50059. this._roll = this._copy.rotation.z;
  50060. this._quaternionRotationYPR();
  50061. }
  50062. this._quaternionToRotationMatrix();
  50063. this._shape = particle._model._shape;
  50064. for (var pt = 0; pt < this._shape.length; pt++) {
  50065. this._vertex.x = this._shape[pt].x;
  50066. this._vertex.y = this._shape[pt].y;
  50067. this._vertex.z = this._shape[pt].z;
  50068. if (particle._model._vertexFunction) {
  50069. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50070. }
  50071. this._vertex.x *= this._copy.scaling.x;
  50072. this._vertex.y *= this._copy.scaling.y;
  50073. this._vertex.z *= this._copy.scaling.z;
  50074. this._vertex.x += this._copy.pivot.x;
  50075. this._vertex.y += this._copy.pivot.y;
  50076. this._vertex.z += this._copy.pivot.z;
  50077. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50078. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50079. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50080. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50081. }
  50082. particle.position.x = 0.0;
  50083. particle.position.y = 0.0;
  50084. particle.position.z = 0.0;
  50085. particle.rotation.x = 0.0;
  50086. particle.rotation.y = 0.0;
  50087. particle.rotation.z = 0.0;
  50088. particle.rotationQuaternion = null;
  50089. particle.scaling.x = 1.0;
  50090. particle.scaling.y = 1.0;
  50091. particle.scaling.z = 1.0;
  50092. };
  50093. /**
  50094. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50095. * @returns the SPS.
  50096. */
  50097. SolidParticleSystem.prototype.rebuildMesh = function () {
  50098. for (var p = 0; p < this.particles.length; p++) {
  50099. this._rebuildParticle(this.particles[p]);
  50100. }
  50101. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50102. return this;
  50103. };
  50104. /**
  50105. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50106. * This method calls `updateParticle()` for each particle of the SPS.
  50107. * For an animated SPS, it is usually called within the render loop.
  50108. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50109. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50110. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50111. * @returns the SPS.
  50112. */
  50113. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50114. if (start === void 0) { start = 0; }
  50115. if (end === void 0) { end = this.nbParticles - 1; }
  50116. if (update === void 0) { update = true; }
  50117. if (!this._updatable) {
  50118. return this;
  50119. }
  50120. // custom beforeUpdate
  50121. this.beforeUpdateParticles(start, end, update);
  50122. this._cam_axisX.x = 1.0;
  50123. this._cam_axisX.y = 0.0;
  50124. this._cam_axisX.z = 0.0;
  50125. this._cam_axisY.x = 0.0;
  50126. this._cam_axisY.y = 1.0;
  50127. this._cam_axisY.z = 0.0;
  50128. this._cam_axisZ.x = 0.0;
  50129. this._cam_axisZ.y = 0.0;
  50130. this._cam_axisZ.z = 1.0;
  50131. // cases when the World Matrix is to be computed first
  50132. if (this.billboard || this._depthSort) {
  50133. this.mesh.computeWorldMatrix(true);
  50134. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  50135. }
  50136. // if the particles will always face the camera
  50137. if (this.billboard) {
  50138. // compute the camera position and un-rotate it by the current mesh rotation
  50139. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  50140. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50141. this._cam_axisZ.normalize();
  50142. // same for camera up vector extracted from the cam view matrix
  50143. var view = this._camera.getViewMatrix(true);
  50144. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  50145. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50146. this._cam_axisY.normalize();
  50147. this._cam_axisX.normalize();
  50148. }
  50149. // if depthSort, compute the camera global position in the mesh local system
  50150. if (this._depthSort) {
  50151. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  50152. }
  50153. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50154. var idx = 0; // current position index in the global array positions32
  50155. var index = 0; // position start index in the global array positions32 of the current particle
  50156. var colidx = 0; // current color index in the global array colors32
  50157. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50158. var uvidx = 0; // current uv index in the global array uvs32
  50159. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50160. var pt = 0; // current index in the particle model shape
  50161. if (this.mesh.isFacetDataEnabled) {
  50162. this._computeBoundingBox = true;
  50163. }
  50164. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  50165. if (this._computeBoundingBox) {
  50166. if (start == 0 && end == this.nbParticles - 1) {
  50167. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50168. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50169. }
  50170. else {
  50171. if (this.mesh._boundingInfo) {
  50172. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  50173. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  50174. }
  50175. }
  50176. }
  50177. // particle loop
  50178. index = this.particles[start]._pos;
  50179. var vpos = (index / 3) | 0;
  50180. colorIndex = vpos * 4;
  50181. uvIndex = vpos * 2;
  50182. for (var p = start; p <= end; p++) {
  50183. this._particle = this.particles[p];
  50184. this._shape = this._particle._model._shape;
  50185. this._shapeUV = this._particle._model._shapeUV;
  50186. // call to custom user function to update the particle properties
  50187. this.updateParticle(this._particle);
  50188. // camera-particle distance for depth sorting
  50189. if (this._depthSort && this._depthSortParticles) {
  50190. var dsp = this.depthSortedParticles[p];
  50191. dsp.ind = this._particle._ind;
  50192. dsp.indicesLength = this._particle._model._indicesLength;
  50193. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  50194. }
  50195. // skip the computations for inactive or already invisible particles
  50196. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  50197. // increment indexes for the next particle
  50198. pt = this._shape.length;
  50199. index += pt * 3;
  50200. colorIndex += pt * 4;
  50201. uvIndex += pt * 2;
  50202. continue;
  50203. }
  50204. if (this._particle.isVisible) {
  50205. this._particle._stillInvisible = false; // un-mark permanent invisibility
  50206. // particle rotation matrix
  50207. if (this.billboard) {
  50208. this._particle.rotation.x = 0.0;
  50209. this._particle.rotation.y = 0.0;
  50210. }
  50211. if (this._computeParticleRotation || this.billboard) {
  50212. if (this._particle.rotationQuaternion) {
  50213. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50214. }
  50215. else {
  50216. this._yaw = this._particle.rotation.y;
  50217. this._pitch = this._particle.rotation.x;
  50218. this._roll = this._particle.rotation.z;
  50219. this._quaternionRotationYPR();
  50220. }
  50221. this._quaternionToRotationMatrix();
  50222. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  50223. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  50224. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  50225. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  50226. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  50227. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  50228. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  50229. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  50230. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  50231. }
  50232. // particle vertex loop
  50233. for (pt = 0; pt < this._shape.length; pt++) {
  50234. idx = index + pt * 3;
  50235. colidx = colorIndex + pt * 4;
  50236. uvidx = uvIndex + pt * 2;
  50237. this._vertex.x = this._shape[pt].x;
  50238. this._vertex.y = this._shape[pt].y;
  50239. this._vertex.z = this._shape[pt].z;
  50240. if (this._computeParticleVertex) {
  50241. this.updateParticleVertex(this._particle, this._vertex, pt);
  50242. }
  50243. // positions
  50244. this._vertex.x *= this._particle.scaling.x;
  50245. this._vertex.y *= this._particle.scaling.y;
  50246. this._vertex.z *= this._particle.scaling.z;
  50247. this._vertex.x += this._particle.pivot.x;
  50248. this._vertex.y += this._particle.pivot.y;
  50249. this._vertex.z += this._particle.pivot.z;
  50250. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50251. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50252. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50253. 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;
  50254. 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;
  50255. 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;
  50256. if (this._computeBoundingBox) {
  50257. if (this._positions32[idx] < this._minimum.x) {
  50258. this._minimum.x = this._positions32[idx];
  50259. }
  50260. if (this._positions32[idx] > this._maximum.x) {
  50261. this._maximum.x = this._positions32[idx];
  50262. }
  50263. if (this._positions32[idx + 1] < this._minimum.y) {
  50264. this._minimum.y = this._positions32[idx + 1];
  50265. }
  50266. if (this._positions32[idx + 1] > this._maximum.y) {
  50267. this._maximum.y = this._positions32[idx + 1];
  50268. }
  50269. if (this._positions32[idx + 2] < this._minimum.z) {
  50270. this._minimum.z = this._positions32[idx + 2];
  50271. }
  50272. if (this._positions32[idx + 2] > this._maximum.z) {
  50273. this._maximum.z = this._positions32[idx + 2];
  50274. }
  50275. }
  50276. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50277. if (!this._computeParticleVertex) {
  50278. this._normal.x = this._fixedNormal32[idx];
  50279. this._normal.y = this._fixedNormal32[idx + 1];
  50280. this._normal.z = this._fixedNormal32[idx + 2];
  50281. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  50282. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  50283. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  50284. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50285. 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;
  50286. 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;
  50287. }
  50288. if (this._computeParticleColor && this._particle.color) {
  50289. this._colors32[colidx] = this._particle.color.r;
  50290. this._colors32[colidx + 1] = this._particle.color.g;
  50291. this._colors32[colidx + 2] = this._particle.color.b;
  50292. this._colors32[colidx + 3] = this._particle.color.a;
  50293. }
  50294. if (this._computeParticleTexture) {
  50295. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50296. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50297. }
  50298. }
  50299. }
  50300. else {
  50301. this._particle._stillInvisible = true; // mark the particle as invisible
  50302. for (pt = 0; pt < this._shape.length; pt++) {
  50303. idx = index + pt * 3;
  50304. colidx = colorIndex + pt * 4;
  50305. uvidx = uvIndex + pt * 2;
  50306. this._positions32[idx] = 0.0;
  50307. this._positions32[idx + 1] = 0.0;
  50308. this._positions32[idx + 2] = 0.0;
  50309. this._normals32[idx] = 0.0;
  50310. this._normals32[idx + 1] = 0.0;
  50311. this._normals32[idx + 2] = 0.0;
  50312. if (this._computeParticleColor && this._particle.color) {
  50313. this._colors32[colidx] = this._particle.color.r;
  50314. this._colors32[colidx + 1] = this._particle.color.g;
  50315. this._colors32[colidx + 2] = this._particle.color.b;
  50316. this._colors32[colidx + 3] = this._particle.color.a;
  50317. }
  50318. if (this._computeParticleTexture) {
  50319. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50320. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50321. }
  50322. }
  50323. }
  50324. // if the particle intersections must be computed : update the bbInfo
  50325. if (this._particlesIntersect) {
  50326. var bInfo = this._particle._boundingInfo;
  50327. var bBox = bInfo.boundingBox;
  50328. var bSphere = bInfo.boundingSphere;
  50329. if (!this._bSphereOnly) {
  50330. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50331. for (var b = 0; b < bBox.vectors.length; b++) {
  50332. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50333. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50334. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50335. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50336. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50337. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50338. 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;
  50339. 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;
  50340. 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;
  50341. }
  50342. bBox._update(this.mesh._worldMatrix);
  50343. }
  50344. // place and scale the particle bouding sphere in the SPS local system, then update it
  50345. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50346. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50347. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50348. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50349. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50350. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50351. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50352. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50353. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50354. 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));
  50355. bSphere._update(this.mesh._worldMatrix);
  50356. }
  50357. // increment indexes for the next particle
  50358. index = idx + 3;
  50359. colorIndex = colidx + 4;
  50360. uvIndex = uvidx + 2;
  50361. }
  50362. // if the VBO must be updated
  50363. if (update) {
  50364. if (this._computeParticleColor) {
  50365. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50366. }
  50367. if (this._computeParticleTexture) {
  50368. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50369. }
  50370. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50371. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50372. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50373. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50374. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50375. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50376. for (var i = 0; i < this._normals32.length; i++) {
  50377. this._fixedNormal32[i] = this._normals32[i];
  50378. }
  50379. }
  50380. if (!this.mesh.areNormalsFrozen) {
  50381. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50382. }
  50383. }
  50384. if (this._depthSort && this._depthSortParticles) {
  50385. this.depthSortedParticles.sort(this._depthSortFunction);
  50386. var dspl = this.depthSortedParticles.length;
  50387. var sorted = 0;
  50388. var lind = 0;
  50389. var sind = 0;
  50390. var sid = 0;
  50391. for (sorted = 0; sorted < dspl; sorted++) {
  50392. lind = this.depthSortedParticles[sorted].indicesLength;
  50393. sind = this.depthSortedParticles[sorted].ind;
  50394. for (var i = 0; i < lind; i++) {
  50395. this._indices32[sid] = this._indices[sind + i];
  50396. sid++;
  50397. }
  50398. }
  50399. this.mesh.updateIndices(this._indices32);
  50400. }
  50401. }
  50402. if (this._computeBoundingBox) {
  50403. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50404. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50405. }
  50406. this.afterUpdateParticles(start, end, update);
  50407. return this;
  50408. };
  50409. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50410. this._halfroll = this._roll * 0.5;
  50411. this._halfpitch = this._pitch * 0.5;
  50412. this._halfyaw = this._yaw * 0.5;
  50413. this._sinRoll = Math.sin(this._halfroll);
  50414. this._cosRoll = Math.cos(this._halfroll);
  50415. this._sinPitch = Math.sin(this._halfpitch);
  50416. this._cosPitch = Math.cos(this._halfpitch);
  50417. this._sinYaw = Math.sin(this._halfyaw);
  50418. this._cosYaw = Math.cos(this._halfyaw);
  50419. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50420. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50421. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50422. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50423. };
  50424. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50425. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50426. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50427. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50428. this._rotMatrix.m[3] = 0;
  50429. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50430. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50431. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50432. this._rotMatrix.m[7] = 0;
  50433. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50434. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50435. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50436. this._rotMatrix.m[11] = 0;
  50437. this._rotMatrix.m[12] = 0;
  50438. this._rotMatrix.m[13] = 0;
  50439. this._rotMatrix.m[14] = 0;
  50440. this._rotMatrix.m[15] = 1.0;
  50441. };
  50442. /**
  50443. * Disposes the SPS.
  50444. */
  50445. SolidParticleSystem.prototype.dispose = function () {
  50446. this.mesh.dispose();
  50447. this.vars = null;
  50448. // drop references to internal big arrays for the GC
  50449. this._positions = null;
  50450. this._indices = null;
  50451. this._normals = null;
  50452. this._uvs = null;
  50453. this._colors = null;
  50454. this._indices32 = null;
  50455. this._positions32 = null;
  50456. this._normals32 = null;
  50457. this._fixedNormal32 = null;
  50458. this._uvs32 = null;
  50459. this._colors32 = null;
  50460. this.pickedParticles = null;
  50461. };
  50462. /**
  50463. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50464. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50465. * @returns the SPS.
  50466. */
  50467. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50468. if (!this._isVisibilityBoxLocked) {
  50469. this.mesh.refreshBoundingInfo();
  50470. }
  50471. return this;
  50472. };
  50473. /**
  50474. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50475. * @param size the size (float) of the visibility box
  50476. * note : this doesn't lock the SPS mesh bounding box.
  50477. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50478. */
  50479. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50480. var vis = size / 2;
  50481. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50482. };
  50483. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50484. /**
  50485. * Gets whether the SPS as always visible or not
  50486. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50487. */
  50488. get: function () {
  50489. return this._alwaysVisible;
  50490. },
  50491. /**
  50492. * Sets the SPS as always visible or not
  50493. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50494. */
  50495. set: function (val) {
  50496. this._alwaysVisible = val;
  50497. this.mesh.alwaysSelectAsActiveMesh = val;
  50498. },
  50499. enumerable: true,
  50500. configurable: true
  50501. });
  50502. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50503. /**
  50504. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50505. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50506. */
  50507. get: function () {
  50508. return this._isVisibilityBoxLocked;
  50509. },
  50510. /**
  50511. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50512. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50513. */
  50514. set: function (val) {
  50515. this._isVisibilityBoxLocked = val;
  50516. var boundingInfo = this.mesh.getBoundingInfo();
  50517. boundingInfo.isLocked = val;
  50518. },
  50519. enumerable: true,
  50520. configurable: true
  50521. });
  50522. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50523. /**
  50524. * Gets if `setParticles()` computes the particle rotations or not.
  50525. * Default value : true. The SPS is faster when it's set to false.
  50526. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50527. */
  50528. get: function () {
  50529. return this._computeParticleRotation;
  50530. },
  50531. /**
  50532. * Tells to `setParticles()` to compute the particle rotations or not.
  50533. * Default value : true. The SPS is faster when it's set to false.
  50534. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50535. */
  50536. set: function (val) {
  50537. this._computeParticleRotation = val;
  50538. },
  50539. enumerable: true,
  50540. configurable: true
  50541. });
  50542. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50543. /**
  50544. * Gets if `setParticles()` computes the particle colors or not.
  50545. * Default value : true. The SPS is faster when it's set to false.
  50546. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50547. */
  50548. get: function () {
  50549. return this._computeParticleColor;
  50550. },
  50551. /**
  50552. * Tells to `setParticles()` to compute the particle colors or not.
  50553. * Default value : true. The SPS is faster when it's set to false.
  50554. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50555. */
  50556. set: function (val) {
  50557. this._computeParticleColor = val;
  50558. },
  50559. enumerable: true,
  50560. configurable: true
  50561. });
  50562. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50563. /**
  50564. * Gets if `setParticles()` computes the particle textures or not.
  50565. * Default value : true. The SPS is faster when it's set to false.
  50566. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50567. */
  50568. get: function () {
  50569. return this._computeParticleTexture;
  50570. },
  50571. set: function (val) {
  50572. this._computeParticleTexture = val;
  50573. },
  50574. enumerable: true,
  50575. configurable: true
  50576. });
  50577. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50578. /**
  50579. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50580. * Default value : false. The SPS is faster when it's set to false.
  50581. * Note : the particle custom vertex positions aren't stored values.
  50582. */
  50583. get: function () {
  50584. return this._computeParticleVertex;
  50585. },
  50586. /**
  50587. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50588. * Default value : false. The SPS is faster when it's set to false.
  50589. * Note : the particle custom vertex positions aren't stored values.
  50590. */
  50591. set: function (val) {
  50592. this._computeParticleVertex = val;
  50593. },
  50594. enumerable: true,
  50595. configurable: true
  50596. });
  50597. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50598. /**
  50599. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50600. */
  50601. get: function () {
  50602. return this._computeBoundingBox;
  50603. },
  50604. /**
  50605. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50606. */
  50607. set: function (val) {
  50608. this._computeBoundingBox = val;
  50609. },
  50610. enumerable: true,
  50611. configurable: true
  50612. });
  50613. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50614. /**
  50615. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50616. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50617. * Default : `true`
  50618. */
  50619. get: function () {
  50620. return this._depthSortParticles;
  50621. },
  50622. /**
  50623. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50624. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50625. * Default : `true`
  50626. */
  50627. set: function (val) {
  50628. this._depthSortParticles = val;
  50629. },
  50630. enumerable: true,
  50631. configurable: true
  50632. });
  50633. // =======================================================================
  50634. // Particle behavior logic
  50635. // these following methods may be overwritten by the user to fit his needs
  50636. /**
  50637. * This function does nothing. It may be overwritten to set all the particle first values.
  50638. * The SPS doesn't call this function, you may have to call it by your own.
  50639. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50640. */
  50641. SolidParticleSystem.prototype.initParticles = function () {
  50642. };
  50643. /**
  50644. * This function does nothing. It may be overwritten to recycle a particle.
  50645. * The SPS doesn't call this function, you may have to call it by your own.
  50646. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50647. * @param particle The particle to recycle
  50648. * @returns the recycled particle
  50649. */
  50650. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50651. return particle;
  50652. };
  50653. /**
  50654. * Updates a particle : this function should be overwritten by the user.
  50655. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50656. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50657. * @example : just set a particle position or velocity and recycle conditions
  50658. * @param particle The particle to update
  50659. * @returns the updated particle
  50660. */
  50661. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50662. return particle;
  50663. };
  50664. /**
  50665. * Updates a vertex of a particle : it can be overwritten by the user.
  50666. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50667. * @param particle the current particle
  50668. * @param vertex the current index of the current particle
  50669. * @param pt the index of the current vertex in the particle shape
  50670. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50671. * @example : just set a vertex particle position
  50672. * @returns the updated vertex
  50673. */
  50674. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50675. return vertex;
  50676. };
  50677. /**
  50678. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50679. * This does nothing and may be overwritten by the user.
  50680. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50681. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50682. * @param update the boolean update value actually passed to setParticles()
  50683. */
  50684. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50685. };
  50686. /**
  50687. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50688. * This will be passed three parameters.
  50689. * This does nothing and may be overwritten by the user.
  50690. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50691. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50692. * @param update the boolean update value actually passed to setParticles()
  50693. */
  50694. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50695. };
  50696. return SolidParticleSystem;
  50697. }());
  50698. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50699. })(BABYLON || (BABYLON = {}));
  50700. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50701. var BABYLON;
  50702. (function (BABYLON) {
  50703. var ShaderMaterial = /** @class */ (function (_super) {
  50704. __extends(ShaderMaterial, _super);
  50705. function ShaderMaterial(name, scene, shaderPath, options) {
  50706. var _this = _super.call(this, name, scene) || this;
  50707. _this._textures = {};
  50708. _this._textureArrays = {};
  50709. _this._floats = {};
  50710. _this._ints = {};
  50711. _this._floatsArrays = {};
  50712. _this._colors3 = {};
  50713. _this._colors3Arrays = {};
  50714. _this._colors4 = {};
  50715. _this._vectors2 = {};
  50716. _this._vectors3 = {};
  50717. _this._vectors4 = {};
  50718. _this._matrices = {};
  50719. _this._matrices3x3 = {};
  50720. _this._matrices2x2 = {};
  50721. _this._vectors2Arrays = {};
  50722. _this._vectors3Arrays = {};
  50723. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50724. _this._shaderPath = shaderPath;
  50725. options.needAlphaBlending = options.needAlphaBlending || false;
  50726. options.needAlphaTesting = options.needAlphaTesting || false;
  50727. options.attributes = options.attributes || ["position", "normal", "uv"];
  50728. options.uniforms = options.uniforms || ["worldViewProjection"];
  50729. options.uniformBuffers = options.uniformBuffers || [];
  50730. options.samplers = options.samplers || [];
  50731. options.defines = options.defines || [];
  50732. _this._options = options;
  50733. return _this;
  50734. }
  50735. ShaderMaterial.prototype.getClassName = function () {
  50736. return "ShaderMaterial";
  50737. };
  50738. ShaderMaterial.prototype.needAlphaBlending = function () {
  50739. return this._options.needAlphaBlending;
  50740. };
  50741. ShaderMaterial.prototype.needAlphaTesting = function () {
  50742. return this._options.needAlphaTesting;
  50743. };
  50744. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50745. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50746. this._options.uniforms.push(uniformName);
  50747. }
  50748. };
  50749. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50750. if (this._options.samplers.indexOf(name) === -1) {
  50751. this._options.samplers.push(name);
  50752. }
  50753. this._textures[name] = texture;
  50754. return this;
  50755. };
  50756. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50757. if (this._options.samplers.indexOf(name) === -1) {
  50758. this._options.samplers.push(name);
  50759. }
  50760. this._checkUniform(name);
  50761. this._textureArrays[name] = textures;
  50762. return this;
  50763. };
  50764. ShaderMaterial.prototype.setFloat = function (name, value) {
  50765. this._checkUniform(name);
  50766. this._floats[name] = value;
  50767. return this;
  50768. };
  50769. ShaderMaterial.prototype.setInt = function (name, value) {
  50770. this._checkUniform(name);
  50771. this._ints[name] = value;
  50772. return this;
  50773. };
  50774. ShaderMaterial.prototype.setFloats = function (name, value) {
  50775. this._checkUniform(name);
  50776. this._floatsArrays[name] = value;
  50777. return this;
  50778. };
  50779. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50780. this._checkUniform(name);
  50781. this._colors3[name] = value;
  50782. return this;
  50783. };
  50784. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50785. this._checkUniform(name);
  50786. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50787. color.toArray(arr, arr.length);
  50788. return arr;
  50789. }, []);
  50790. return this;
  50791. };
  50792. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50793. this._checkUniform(name);
  50794. this._colors4[name] = value;
  50795. return this;
  50796. };
  50797. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50798. this._checkUniform(name);
  50799. this._vectors2[name] = value;
  50800. return this;
  50801. };
  50802. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50803. this._checkUniform(name);
  50804. this._vectors3[name] = value;
  50805. return this;
  50806. };
  50807. ShaderMaterial.prototype.setVector4 = function (name, value) {
  50808. this._checkUniform(name);
  50809. this._vectors4[name] = value;
  50810. return this;
  50811. };
  50812. ShaderMaterial.prototype.setMatrix = function (name, value) {
  50813. this._checkUniform(name);
  50814. this._matrices[name] = value;
  50815. return this;
  50816. };
  50817. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  50818. this._checkUniform(name);
  50819. this._matrices3x3[name] = value;
  50820. return this;
  50821. };
  50822. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  50823. this._checkUniform(name);
  50824. this._matrices2x2[name] = value;
  50825. return this;
  50826. };
  50827. ShaderMaterial.prototype.setArray2 = function (name, value) {
  50828. this._checkUniform(name);
  50829. this._vectors2Arrays[name] = value;
  50830. return this;
  50831. };
  50832. ShaderMaterial.prototype.setArray3 = function (name, value) {
  50833. this._checkUniform(name);
  50834. this._vectors3Arrays[name] = value;
  50835. return this;
  50836. };
  50837. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50838. if (!mesh) {
  50839. return true;
  50840. }
  50841. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  50842. return false;
  50843. }
  50844. return false;
  50845. };
  50846. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  50847. var scene = this.getScene();
  50848. var engine = scene.getEngine();
  50849. if (!this.checkReadyOnEveryCall) {
  50850. if (this._renderId === scene.getRenderId()) {
  50851. if (this._checkCache(scene, mesh, useInstances)) {
  50852. return true;
  50853. }
  50854. }
  50855. }
  50856. // Instances
  50857. var defines = [];
  50858. var attribs = [];
  50859. var fallbacks = new BABYLON.EffectFallbacks();
  50860. if (useInstances) {
  50861. defines.push("#define INSTANCES");
  50862. }
  50863. for (var index = 0; index < this._options.defines.length; index++) {
  50864. defines.push(this._options.defines[index]);
  50865. }
  50866. for (var index = 0; index < this._options.attributes.length; index++) {
  50867. attribs.push(this._options.attributes[index]);
  50868. }
  50869. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50870. attribs.push(BABYLON.VertexBuffer.ColorKind);
  50871. defines.push("#define VERTEXCOLOR");
  50872. }
  50873. // Bones
  50874. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  50875. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50876. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50877. if (mesh.numBoneInfluencers > 4) {
  50878. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50879. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50880. }
  50881. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50882. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50883. fallbacks.addCPUSkinningFallback(0, mesh);
  50884. if (this._options.uniforms.indexOf("mBones") === -1) {
  50885. this._options.uniforms.push("mBones");
  50886. }
  50887. }
  50888. else {
  50889. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50890. }
  50891. // Textures
  50892. for (var name in this._textures) {
  50893. if (!this._textures[name].isReady()) {
  50894. return false;
  50895. }
  50896. }
  50897. // Alpha test
  50898. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  50899. defines.push("#define ALPHATEST");
  50900. }
  50901. var previousEffect = this._effect;
  50902. var join = defines.join("\n");
  50903. this._effect = engine.createEffect(this._shaderPath, {
  50904. attributes: attribs,
  50905. uniformsNames: this._options.uniforms,
  50906. uniformBuffersNames: this._options.uniformBuffers,
  50907. samplers: this._options.samplers,
  50908. defines: join,
  50909. fallbacks: fallbacks,
  50910. onCompiled: this.onCompiled,
  50911. onError: this.onError
  50912. }, engine);
  50913. if (!this._effect.isReady()) {
  50914. return false;
  50915. }
  50916. if (previousEffect !== this._effect) {
  50917. scene.resetCachedMaterial();
  50918. }
  50919. this._renderId = scene.getRenderId();
  50920. return true;
  50921. };
  50922. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  50923. var scene = this.getScene();
  50924. if (!this._effect) {
  50925. return;
  50926. }
  50927. if (this._options.uniforms.indexOf("world") !== -1) {
  50928. this._effect.setMatrix("world", world);
  50929. }
  50930. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50931. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50932. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50933. }
  50934. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50935. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50936. }
  50937. };
  50938. ShaderMaterial.prototype.bind = function (world, mesh) {
  50939. // Std values
  50940. this.bindOnlyWorldMatrix(world);
  50941. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50942. if (this._options.uniforms.indexOf("view") !== -1) {
  50943. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50944. }
  50945. if (this._options.uniforms.indexOf("projection") !== -1) {
  50946. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50947. }
  50948. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50949. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50950. }
  50951. // Bones
  50952. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50953. var name;
  50954. // Texture
  50955. for (name in this._textures) {
  50956. this._effect.setTexture(name, this._textures[name]);
  50957. }
  50958. // Texture arrays
  50959. for (name in this._textureArrays) {
  50960. this._effect.setTextureArray(name, this._textureArrays[name]);
  50961. }
  50962. // Int
  50963. for (name in this._ints) {
  50964. this._effect.setInt(name, this._ints[name]);
  50965. }
  50966. // Float
  50967. for (name in this._floats) {
  50968. this._effect.setFloat(name, this._floats[name]);
  50969. }
  50970. // Floats
  50971. for (name in this._floatsArrays) {
  50972. this._effect.setArray(name, this._floatsArrays[name]);
  50973. }
  50974. // Color3
  50975. for (name in this._colors3) {
  50976. this._effect.setColor3(name, this._colors3[name]);
  50977. }
  50978. for (name in this._colors3Arrays) {
  50979. this._effect.setArray3(name, this._colors3Arrays[name]);
  50980. }
  50981. // Color4
  50982. for (name in this._colors4) {
  50983. var color = this._colors4[name];
  50984. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50985. }
  50986. // Vector2
  50987. for (name in this._vectors2) {
  50988. this._effect.setVector2(name, this._vectors2[name]);
  50989. }
  50990. // Vector3
  50991. for (name in this._vectors3) {
  50992. this._effect.setVector3(name, this._vectors3[name]);
  50993. }
  50994. // Vector4
  50995. for (name in this._vectors4) {
  50996. this._effect.setVector4(name, this._vectors4[name]);
  50997. }
  50998. // Matrix
  50999. for (name in this._matrices) {
  51000. this._effect.setMatrix(name, this._matrices[name]);
  51001. }
  51002. // Matrix 3x3
  51003. for (name in this._matrices3x3) {
  51004. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  51005. }
  51006. // Matrix 2x2
  51007. for (name in this._matrices2x2) {
  51008. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  51009. }
  51010. // Vector2Array
  51011. for (name in this._vectors2Arrays) {
  51012. this._effect.setArray2(name, this._vectors2Arrays[name]);
  51013. }
  51014. // Vector3Array
  51015. for (name in this._vectors3Arrays) {
  51016. this._effect.setArray3(name, this._vectors3Arrays[name]);
  51017. }
  51018. }
  51019. this._afterBind(mesh);
  51020. };
  51021. ShaderMaterial.prototype.getActiveTextures = function () {
  51022. var activeTextures = _super.prototype.getActiveTextures.call(this);
  51023. for (var name in this._textures) {
  51024. activeTextures.push(this._textures[name]);
  51025. }
  51026. for (var name in this._textureArrays) {
  51027. var array = this._textureArrays[name];
  51028. for (var index = 0; index < array.length; index++) {
  51029. activeTextures.push(array[index]);
  51030. }
  51031. }
  51032. return activeTextures;
  51033. };
  51034. ShaderMaterial.prototype.hasTexture = function (texture) {
  51035. if (_super.prototype.hasTexture.call(this, texture)) {
  51036. return true;
  51037. }
  51038. for (var name in this._textures) {
  51039. if (this._textures[name] === texture) {
  51040. return true;
  51041. }
  51042. }
  51043. for (var name in this._textureArrays) {
  51044. var array = this._textureArrays[name];
  51045. for (var index = 0; index < array.length; index++) {
  51046. if (array[index] === texture) {
  51047. return true;
  51048. }
  51049. }
  51050. }
  51051. return false;
  51052. };
  51053. ShaderMaterial.prototype.clone = function (name) {
  51054. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  51055. return newShaderMaterial;
  51056. };
  51057. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51058. if (forceDisposeTextures) {
  51059. var name;
  51060. for (name in this._textures) {
  51061. this._textures[name].dispose();
  51062. }
  51063. for (name in this._textureArrays) {
  51064. var array = this._textureArrays[name];
  51065. for (var index = 0; index < array.length; index++) {
  51066. array[index].dispose();
  51067. }
  51068. }
  51069. }
  51070. this._textures = {};
  51071. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51072. };
  51073. ShaderMaterial.prototype.serialize = function () {
  51074. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51075. serializationObject.customType = "BABYLON.ShaderMaterial";
  51076. serializationObject.options = this._options;
  51077. serializationObject.shaderPath = this._shaderPath;
  51078. var name;
  51079. // Texture
  51080. serializationObject.textures = {};
  51081. for (name in this._textures) {
  51082. serializationObject.textures[name] = this._textures[name].serialize();
  51083. }
  51084. // Texture arrays
  51085. serializationObject.textureArrays = {};
  51086. for (name in this._textureArrays) {
  51087. serializationObject.textureArrays[name] = [];
  51088. var array = this._textureArrays[name];
  51089. for (var index = 0; index < array.length; index++) {
  51090. serializationObject.textureArrays[name].push(array[index].serialize());
  51091. }
  51092. }
  51093. // Float
  51094. serializationObject.floats = {};
  51095. for (name in this._floats) {
  51096. serializationObject.floats[name] = this._floats[name];
  51097. }
  51098. // Float s
  51099. serializationObject.FloatArrays = {};
  51100. for (name in this._floatsArrays) {
  51101. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  51102. }
  51103. // Color3
  51104. serializationObject.colors3 = {};
  51105. for (name in this._colors3) {
  51106. serializationObject.colors3[name] = this._colors3[name].asArray();
  51107. }
  51108. // Color3 array
  51109. serializationObject.colors3Arrays = {};
  51110. for (name in this._colors3Arrays) {
  51111. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  51112. }
  51113. // Color4
  51114. serializationObject.colors4 = {};
  51115. for (name in this._colors4) {
  51116. serializationObject.colors4[name] = this._colors4[name].asArray();
  51117. }
  51118. // Vector2
  51119. serializationObject.vectors2 = {};
  51120. for (name in this._vectors2) {
  51121. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  51122. }
  51123. // Vector3
  51124. serializationObject.vectors3 = {};
  51125. for (name in this._vectors3) {
  51126. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  51127. }
  51128. // Vector4
  51129. serializationObject.vectors4 = {};
  51130. for (name in this._vectors4) {
  51131. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  51132. }
  51133. // Matrix
  51134. serializationObject.matrices = {};
  51135. for (name in this._matrices) {
  51136. serializationObject.matrices[name] = this._matrices[name].asArray();
  51137. }
  51138. // Matrix 3x3
  51139. serializationObject.matrices3x3 = {};
  51140. for (name in this._matrices3x3) {
  51141. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  51142. }
  51143. // Matrix 2x2
  51144. serializationObject.matrices2x2 = {};
  51145. for (name in this._matrices2x2) {
  51146. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  51147. }
  51148. // Vector2Array
  51149. serializationObject.vectors2Arrays = {};
  51150. for (name in this._vectors2Arrays) {
  51151. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  51152. }
  51153. // Vector3Array
  51154. serializationObject.vectors3Arrays = {};
  51155. for (name in this._vectors3Arrays) {
  51156. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  51157. }
  51158. return serializationObject;
  51159. };
  51160. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  51161. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  51162. var name;
  51163. // Texture
  51164. for (name in source.textures) {
  51165. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  51166. }
  51167. // Texture arrays
  51168. for (name in source.textureArrays) {
  51169. var array = source.textureArrays[name];
  51170. var textureArray = new Array();
  51171. for (var index = 0; index < array.length; index++) {
  51172. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  51173. }
  51174. material.setTextureArray(name, textureArray);
  51175. }
  51176. // Float
  51177. for (name in source.floats) {
  51178. material.setFloat(name, source.floats[name]);
  51179. }
  51180. // Float s
  51181. for (name in source.floatsArrays) {
  51182. material.setFloats(name, source.floatsArrays[name]);
  51183. }
  51184. // Color3
  51185. for (name in source.colors3) {
  51186. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  51187. }
  51188. // Color3 arrays
  51189. for (name in source.colors3Arrays) {
  51190. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  51191. if (i % 3 === 0) {
  51192. arr.push([num]);
  51193. }
  51194. else {
  51195. arr[arr.length - 1].push(num);
  51196. }
  51197. return arr;
  51198. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  51199. material.setColor3Array(name, colors);
  51200. }
  51201. // Color4
  51202. for (name in source.colors4) {
  51203. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  51204. }
  51205. // Vector2
  51206. for (name in source.vectors2) {
  51207. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  51208. }
  51209. // Vector3
  51210. for (name in source.vectors3) {
  51211. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  51212. }
  51213. // Vector4
  51214. for (name in source.vectors4) {
  51215. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  51216. }
  51217. // Matrix
  51218. for (name in source.matrices) {
  51219. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  51220. }
  51221. // Matrix 3x3
  51222. for (name in source.matrices3x3) {
  51223. material.setMatrix3x3(name, source.matrices3x3[name]);
  51224. }
  51225. // Matrix 2x2
  51226. for (name in source.matrices2x2) {
  51227. material.setMatrix2x2(name, source.matrices2x2[name]);
  51228. }
  51229. // Vector2Array
  51230. for (name in source.vectors2Arrays) {
  51231. material.setArray2(name, source.vectors2Arrays[name]);
  51232. }
  51233. // Vector3Array
  51234. for (name in source.vectors3Arrays) {
  51235. material.setArray3(name, source.vectors3Arrays[name]);
  51236. }
  51237. return material;
  51238. };
  51239. return ShaderMaterial;
  51240. }(BABYLON.Material));
  51241. BABYLON.ShaderMaterial = ShaderMaterial;
  51242. })(BABYLON || (BABYLON = {}));
  51243. //# sourceMappingURL=babylon.shaderMaterial.js.map
  51244. var BABYLON;
  51245. (function (BABYLON) {
  51246. var GroundMesh = /** @class */ (function (_super) {
  51247. __extends(GroundMesh, _super);
  51248. function GroundMesh(name, scene) {
  51249. var _this = _super.call(this, name, scene) || this;
  51250. _this.generateOctree = false;
  51251. return _this;
  51252. }
  51253. GroundMesh.prototype.getClassName = function () {
  51254. return "GroundMesh";
  51255. };
  51256. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  51257. get: function () {
  51258. return Math.min(this._subdivisionsX, this._subdivisionsY);
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  51264. get: function () {
  51265. return this._subdivisionsX;
  51266. },
  51267. enumerable: true,
  51268. configurable: true
  51269. });
  51270. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  51271. get: function () {
  51272. return this._subdivisionsY;
  51273. },
  51274. enumerable: true,
  51275. configurable: true
  51276. });
  51277. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  51278. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  51279. this._subdivisionsX = chunksCount;
  51280. this._subdivisionsY = chunksCount;
  51281. this.subdivide(chunksCount);
  51282. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  51283. };
  51284. /**
  51285. * Returns a height (y) value in the Worl system :
  51286. * the ground altitude at the coordinates (x, z) expressed in the World system.
  51287. * Returns the ground y position if (x, z) are outside the ground surface.
  51288. */
  51289. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  51290. var world = this.getWorldMatrix();
  51291. var invMat = BABYLON.Tmp.Matrix[5];
  51292. world.invertToRef(invMat);
  51293. var tmpVect = BABYLON.Tmp.Vector3[8];
  51294. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  51295. x = tmpVect.x;
  51296. z = tmpVect.z;
  51297. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51298. return this.position.y;
  51299. }
  51300. if (!this._heightQuads || this._heightQuads.length == 0) {
  51301. this._initHeightQuads();
  51302. this._computeHeightQuads();
  51303. }
  51304. var facet = this._getFacetAt(x, z);
  51305. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  51306. // return y in the World system
  51307. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  51308. return tmpVect.y;
  51309. };
  51310. /**
  51311. * Returns a normalized vector (Vector3) orthogonal to the ground
  51312. * at the ground coordinates (x, z) expressed in the World system.
  51313. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  51314. */
  51315. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  51316. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  51317. this.getNormalAtCoordinatesToRef(x, z, normal);
  51318. return normal;
  51319. };
  51320. /**
  51321. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  51322. * at the ground coordinates (x, z) expressed in the World system.
  51323. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  51324. * Returns the GroundMesh.
  51325. */
  51326. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  51327. var world = this.getWorldMatrix();
  51328. var tmpMat = BABYLON.Tmp.Matrix[5];
  51329. world.invertToRef(tmpMat);
  51330. var tmpVect = BABYLON.Tmp.Vector3[8];
  51331. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  51332. x = tmpVect.x;
  51333. z = tmpVect.z;
  51334. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51335. return this;
  51336. }
  51337. if (!this._heightQuads || this._heightQuads.length == 0) {
  51338. this._initHeightQuads();
  51339. this._computeHeightQuads();
  51340. }
  51341. var facet = this._getFacetAt(x, z);
  51342. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51343. return this;
  51344. };
  51345. /**
  51346. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51347. * if the ground has been updated.
  51348. * This can be used in the render loop.
  51349. * Returns the GroundMesh.
  51350. */
  51351. GroundMesh.prototype.updateCoordinateHeights = function () {
  51352. if (!this._heightQuads || this._heightQuads.length == 0) {
  51353. this._initHeightQuads();
  51354. }
  51355. this._computeHeightQuads();
  51356. return this;
  51357. };
  51358. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51359. GroundMesh.prototype._getFacetAt = function (x, z) {
  51360. // retrieve col and row from x, z coordinates in the ground local system
  51361. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51362. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51363. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51364. var facet;
  51365. if (z < quad.slope.x * x + quad.slope.y) {
  51366. facet = quad.facet1;
  51367. }
  51368. else {
  51369. facet = quad.facet2;
  51370. }
  51371. return facet;
  51372. };
  51373. // Creates and populates the heightMap array with "facet" elements :
  51374. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51375. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51376. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51377. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51378. // Returns the GroundMesh.
  51379. GroundMesh.prototype._initHeightQuads = function () {
  51380. var subdivisionsX = this._subdivisionsX;
  51381. var subdivisionsY = this._subdivisionsY;
  51382. this._heightQuads = new Array();
  51383. for (var row = 0; row < subdivisionsY; row++) {
  51384. for (var col = 0; col < subdivisionsX; col++) {
  51385. 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) };
  51386. this._heightQuads[row * subdivisionsX + col] = quad;
  51387. }
  51388. }
  51389. return this;
  51390. };
  51391. // Compute each quad element values and update the the heightMap array :
  51392. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51393. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51394. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51395. // Returns the GroundMesh.
  51396. GroundMesh.prototype._computeHeightQuads = function () {
  51397. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51398. if (!positions) {
  51399. return this;
  51400. }
  51401. var v1 = BABYLON.Tmp.Vector3[3];
  51402. var v2 = BABYLON.Tmp.Vector3[2];
  51403. var v3 = BABYLON.Tmp.Vector3[1];
  51404. var v4 = BABYLON.Tmp.Vector3[0];
  51405. var v1v2 = BABYLON.Tmp.Vector3[4];
  51406. var v1v3 = BABYLON.Tmp.Vector3[5];
  51407. var v1v4 = BABYLON.Tmp.Vector3[6];
  51408. var norm1 = BABYLON.Tmp.Vector3[7];
  51409. var norm2 = BABYLON.Tmp.Vector3[8];
  51410. var i = 0;
  51411. var j = 0;
  51412. var k = 0;
  51413. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51414. var h = 0;
  51415. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51416. var d2 = 0;
  51417. var subdivisionsX = this._subdivisionsX;
  51418. var subdivisionsY = this._subdivisionsY;
  51419. for (var row = 0; row < subdivisionsY; row++) {
  51420. for (var col = 0; col < subdivisionsX; col++) {
  51421. i = col * 3;
  51422. j = row * (subdivisionsX + 1) * 3;
  51423. k = (row + 1) * (subdivisionsX + 1) * 3;
  51424. v1.x = positions[j + i];
  51425. v1.y = positions[j + i + 1];
  51426. v1.z = positions[j + i + 2];
  51427. v2.x = positions[j + i + 3];
  51428. v2.y = positions[j + i + 4];
  51429. v2.z = positions[j + i + 5];
  51430. v3.x = positions[k + i];
  51431. v3.y = positions[k + i + 1];
  51432. v3.z = positions[k + i + 2];
  51433. v4.x = positions[k + i + 3];
  51434. v4.y = positions[k + i + 4];
  51435. v4.z = positions[k + i + 5];
  51436. // 2D slope V1V4
  51437. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51438. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51439. // facet equations :
  51440. // we compute each facet normal vector
  51441. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51442. // we compute the value d by applying the equation to v1 which belongs to the plane
  51443. // then we store the facet equation in a Vector4
  51444. v2.subtractToRef(v1, v1v2);
  51445. v3.subtractToRef(v1, v1v3);
  51446. v4.subtractToRef(v1, v1v4);
  51447. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51448. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51449. norm1.normalize();
  51450. norm2.normalize();
  51451. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51452. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51453. var quad = this._heightQuads[row * subdivisionsX + col];
  51454. quad.slope.copyFromFloats(cd, h);
  51455. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51456. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51457. }
  51458. }
  51459. return this;
  51460. };
  51461. GroundMesh.prototype.serialize = function (serializationObject) {
  51462. _super.prototype.serialize.call(this, serializationObject);
  51463. serializationObject.subdivisionsX = this._subdivisionsX;
  51464. serializationObject.subdivisionsY = this._subdivisionsY;
  51465. serializationObject.minX = this._minX;
  51466. serializationObject.maxX = this._maxX;
  51467. serializationObject.minZ = this._minZ;
  51468. serializationObject.maxZ = this._maxZ;
  51469. serializationObject.width = this._width;
  51470. serializationObject.height = this._height;
  51471. };
  51472. GroundMesh.Parse = function (parsedMesh, scene) {
  51473. var result = new GroundMesh(parsedMesh.name, scene);
  51474. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51475. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51476. result._minX = parsedMesh.minX;
  51477. result._maxX = parsedMesh.maxX;
  51478. result._minZ = parsedMesh.minZ;
  51479. result._maxZ = parsedMesh.maxZ;
  51480. result._width = parsedMesh.width;
  51481. result._height = parsedMesh.height;
  51482. return result;
  51483. };
  51484. return GroundMesh;
  51485. }(BABYLON.Mesh));
  51486. BABYLON.GroundMesh = GroundMesh;
  51487. })(BABYLON || (BABYLON = {}));
  51488. //# sourceMappingURL=babylon.groundMesh.js.map
  51489. var BABYLON;
  51490. (function (BABYLON) {
  51491. /**
  51492. * Creates an instance based on a source mesh.
  51493. */
  51494. var InstancedMesh = /** @class */ (function (_super) {
  51495. __extends(InstancedMesh, _super);
  51496. function InstancedMesh(name, source) {
  51497. var _this = _super.call(this, name, source.getScene()) || this;
  51498. source.instances.push(_this);
  51499. _this._sourceMesh = source;
  51500. _this.position.copyFrom(source.position);
  51501. _this.rotation.copyFrom(source.rotation);
  51502. _this.scaling.copyFrom(source.scaling);
  51503. if (source.rotationQuaternion) {
  51504. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51505. }
  51506. _this.infiniteDistance = source.infiniteDistance;
  51507. _this.setPivotMatrix(source.getPivotMatrix());
  51508. _this.refreshBoundingInfo();
  51509. _this._syncSubMeshes();
  51510. return _this;
  51511. }
  51512. /**
  51513. * Returns the string "InstancedMesh".
  51514. */
  51515. InstancedMesh.prototype.getClassName = function () {
  51516. return "InstancedMesh";
  51517. };
  51518. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51519. // Methods
  51520. get: function () {
  51521. return this._sourceMesh.receiveShadows;
  51522. },
  51523. enumerable: true,
  51524. configurable: true
  51525. });
  51526. Object.defineProperty(InstancedMesh.prototype, "material", {
  51527. get: function () {
  51528. return this._sourceMesh.material;
  51529. },
  51530. enumerable: true,
  51531. configurable: true
  51532. });
  51533. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51534. get: function () {
  51535. return this._sourceMesh.visibility;
  51536. },
  51537. enumerable: true,
  51538. configurable: true
  51539. });
  51540. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51541. get: function () {
  51542. return this._sourceMesh.skeleton;
  51543. },
  51544. enumerable: true,
  51545. configurable: true
  51546. });
  51547. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51548. get: function () {
  51549. return this._sourceMesh.renderingGroupId;
  51550. },
  51551. enumerable: true,
  51552. configurable: true
  51553. });
  51554. /**
  51555. * Returns the total number of vertices (integer).
  51556. */
  51557. InstancedMesh.prototype.getTotalVertices = function () {
  51558. return this._sourceMesh.getTotalVertices();
  51559. };
  51560. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51561. get: function () {
  51562. return this._sourceMesh;
  51563. },
  51564. enumerable: true,
  51565. configurable: true
  51566. });
  51567. /**
  51568. * Is this node ready to be used/rendered
  51569. * @return {boolean} is it ready
  51570. */
  51571. InstancedMesh.prototype.isReady = function () {
  51572. return this._sourceMesh.isReady(true);
  51573. };
  51574. /**
  51575. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51576. */
  51577. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51578. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51579. };
  51580. /**
  51581. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51582. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51583. * The `data` are either a numeric array either a Float32Array.
  51584. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51585. * 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).
  51586. * Note that a new underlying VertexBuffer object is created each call.
  51587. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51588. *
  51589. * Possible `kind` values :
  51590. * - BABYLON.VertexBuffer.PositionKind
  51591. * - BABYLON.VertexBuffer.UVKind
  51592. * - BABYLON.VertexBuffer.UV2Kind
  51593. * - BABYLON.VertexBuffer.UV3Kind
  51594. * - BABYLON.VertexBuffer.UV4Kind
  51595. * - BABYLON.VertexBuffer.UV5Kind
  51596. * - BABYLON.VertexBuffer.UV6Kind
  51597. * - BABYLON.VertexBuffer.ColorKind
  51598. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51599. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51600. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51601. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51602. *
  51603. * Returns the Mesh.
  51604. */
  51605. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51606. if (this.sourceMesh) {
  51607. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51608. }
  51609. return this.sourceMesh;
  51610. };
  51611. /**
  51612. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51613. * If the mesh has no geometry, it is simply returned as it is.
  51614. * The `data` are either a numeric array either a Float32Array.
  51615. * No new underlying VertexBuffer object is created.
  51616. * 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.
  51617. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51618. *
  51619. * Possible `kind` values :
  51620. * - BABYLON.VertexBuffer.PositionKind
  51621. * - BABYLON.VertexBuffer.UVKind
  51622. * - BABYLON.VertexBuffer.UV2Kind
  51623. * - BABYLON.VertexBuffer.UV3Kind
  51624. * - BABYLON.VertexBuffer.UV4Kind
  51625. * - BABYLON.VertexBuffer.UV5Kind
  51626. * - BABYLON.VertexBuffer.UV6Kind
  51627. * - BABYLON.VertexBuffer.ColorKind
  51628. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51629. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51630. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51631. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51632. *
  51633. * Returns the Mesh.
  51634. */
  51635. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51636. if (this.sourceMesh) {
  51637. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51638. }
  51639. return this.sourceMesh;
  51640. };
  51641. /**
  51642. * Sets the mesh indices.
  51643. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51644. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51645. * This method creates a new index buffer each call.
  51646. * Returns the Mesh.
  51647. */
  51648. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51649. if (totalVertices === void 0) { totalVertices = null; }
  51650. if (this.sourceMesh) {
  51651. this.sourceMesh.setIndices(indices, totalVertices);
  51652. }
  51653. return this.sourceMesh;
  51654. };
  51655. /**
  51656. * Boolean : True if the mesh owns the requested kind of data.
  51657. */
  51658. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51659. return this._sourceMesh.isVerticesDataPresent(kind);
  51660. };
  51661. /**
  51662. * Returns an array of indices (IndicesArray).
  51663. */
  51664. InstancedMesh.prototype.getIndices = function () {
  51665. return this._sourceMesh.getIndices();
  51666. };
  51667. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51668. get: function () {
  51669. return this._sourceMesh._positions;
  51670. },
  51671. enumerable: true,
  51672. configurable: true
  51673. });
  51674. /**
  51675. * Sets a new updated BoundingInfo to the mesh.
  51676. * Returns the mesh.
  51677. */
  51678. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51679. var meshBB = this._sourceMesh.getBoundingInfo();
  51680. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51681. this._updateBoundingInfo();
  51682. return this;
  51683. };
  51684. InstancedMesh.prototype._preActivate = function () {
  51685. if (this._currentLOD) {
  51686. this._currentLOD._preActivate();
  51687. }
  51688. return this;
  51689. };
  51690. InstancedMesh.prototype._activate = function (renderId) {
  51691. if (this._currentLOD) {
  51692. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51693. }
  51694. return this;
  51695. };
  51696. /**
  51697. * Returns the current associated LOD AbstractMesh.
  51698. */
  51699. InstancedMesh.prototype.getLOD = function (camera) {
  51700. if (!camera) {
  51701. return this;
  51702. }
  51703. var boundingInfo = this.getBoundingInfo();
  51704. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51705. if (this._currentLOD === this.sourceMesh) {
  51706. return this;
  51707. }
  51708. return this._currentLOD;
  51709. };
  51710. InstancedMesh.prototype._syncSubMeshes = function () {
  51711. this.releaseSubMeshes();
  51712. if (this._sourceMesh.subMeshes) {
  51713. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51714. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51715. }
  51716. }
  51717. return this;
  51718. };
  51719. InstancedMesh.prototype._generatePointsArray = function () {
  51720. return this._sourceMesh._generatePointsArray();
  51721. };
  51722. /**
  51723. * Creates a new InstancedMesh from the current mesh.
  51724. * - name (string) : the cloned mesh name
  51725. * - newParent (optional Node) : the optional Node to parent the clone to.
  51726. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51727. *
  51728. * Returns the clone.
  51729. */
  51730. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51731. var result = this._sourceMesh.createInstance(name);
  51732. // Deep copy
  51733. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51734. // Bounding info
  51735. this.refreshBoundingInfo();
  51736. // Parent
  51737. if (newParent) {
  51738. result.parent = newParent;
  51739. }
  51740. if (!doNotCloneChildren) {
  51741. // Children
  51742. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51743. var mesh = this.getScene().meshes[index];
  51744. if (mesh.parent === this) {
  51745. mesh.clone(mesh.name, result);
  51746. }
  51747. }
  51748. }
  51749. result.computeWorldMatrix(true);
  51750. return result;
  51751. };
  51752. /**
  51753. * Disposes the InstancedMesh.
  51754. * Returns nothing.
  51755. */
  51756. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51757. // Remove from mesh
  51758. var index = this._sourceMesh.instances.indexOf(this);
  51759. this._sourceMesh.instances.splice(index, 1);
  51760. _super.prototype.dispose.call(this, doNotRecurse);
  51761. };
  51762. return InstancedMesh;
  51763. }(BABYLON.AbstractMesh));
  51764. BABYLON.InstancedMesh = InstancedMesh;
  51765. })(BABYLON || (BABYLON = {}));
  51766. //# sourceMappingURL=babylon.instancedMesh.js.map
  51767. var BABYLON;
  51768. (function (BABYLON) {
  51769. var LinesMesh = /** @class */ (function (_super) {
  51770. __extends(LinesMesh, _super);
  51771. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51772. if (scene === void 0) { scene = null; }
  51773. if (parent === void 0) { parent = null; }
  51774. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51775. _this.useVertexColor = useVertexColor;
  51776. _this.useVertexAlpha = useVertexAlpha;
  51777. _this.color = new BABYLON.Color3(1, 1, 1);
  51778. _this.alpha = 1;
  51779. if (source) {
  51780. _this.color = source.color.clone();
  51781. _this.alpha = source.alpha;
  51782. _this.useVertexColor = source.useVertexColor;
  51783. _this.useVertexAlpha = source.useVertexAlpha;
  51784. }
  51785. _this._intersectionThreshold = 0.1;
  51786. var defines = [];
  51787. var options = {
  51788. attributes: [BABYLON.VertexBuffer.PositionKind],
  51789. uniforms: ["world", "viewProjection"],
  51790. needAlphaBlending: true,
  51791. defines: defines
  51792. };
  51793. if (useVertexAlpha === false) {
  51794. options.needAlphaBlending = false;
  51795. }
  51796. if (!useVertexColor) {
  51797. options.uniforms.push("color");
  51798. }
  51799. else {
  51800. options.defines.push("#define VERTEXCOLOR");
  51801. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51802. }
  51803. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51804. return _this;
  51805. }
  51806. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51807. /**
  51808. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51809. * This margin is expressed in world space coordinates, so its value may vary.
  51810. * Default value is 0.1
  51811. * @returns the intersection Threshold value.
  51812. */
  51813. get: function () {
  51814. return this._intersectionThreshold;
  51815. },
  51816. /**
  51817. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51818. * This margin is expressed in world space coordinates, so its value may vary.
  51819. * @param value the new threshold to apply
  51820. */
  51821. set: function (value) {
  51822. if (this._intersectionThreshold === value) {
  51823. return;
  51824. }
  51825. this._intersectionThreshold = value;
  51826. if (this.geometry) {
  51827. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  51828. }
  51829. },
  51830. enumerable: true,
  51831. configurable: true
  51832. });
  51833. /**
  51834. * Returns the string "LineMesh"
  51835. */
  51836. LinesMesh.prototype.getClassName = function () {
  51837. return "LinesMesh";
  51838. };
  51839. Object.defineProperty(LinesMesh.prototype, "material", {
  51840. get: function () {
  51841. return this._colorShader;
  51842. },
  51843. set: function (value) {
  51844. // Do nothing
  51845. },
  51846. enumerable: true,
  51847. configurable: true
  51848. });
  51849. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  51850. get: function () {
  51851. return false;
  51852. },
  51853. enumerable: true,
  51854. configurable: true
  51855. });
  51856. LinesMesh.prototype.createInstance = function (name) {
  51857. throw new Error("LinesMeshes do not support createInstance.");
  51858. };
  51859. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  51860. if (!this._geometry) {
  51861. return this;
  51862. }
  51863. // VBOs
  51864. this._geometry._bind(this._colorShader.getEffect());
  51865. // Color
  51866. if (!this.useVertexColor) {
  51867. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  51868. }
  51869. return this;
  51870. };
  51871. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  51872. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  51873. return this;
  51874. }
  51875. var engine = this.getScene().getEngine();
  51876. // Draw order
  51877. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  51878. return this;
  51879. };
  51880. LinesMesh.prototype.dispose = function (doNotRecurse) {
  51881. this._colorShader.dispose();
  51882. _super.prototype.dispose.call(this, doNotRecurse);
  51883. };
  51884. /**
  51885. * Returns a new LineMesh object cloned from the current one.
  51886. */
  51887. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51888. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  51889. };
  51890. return LinesMesh;
  51891. }(BABYLON.Mesh));
  51892. BABYLON.LinesMesh = LinesMesh;
  51893. })(BABYLON || (BABYLON = {}));
  51894. //# sourceMappingURL=babylon.linesMesh.js.map
  51895. var BABYLON;
  51896. (function (BABYLON) {
  51897. var MeshBuilder = /** @class */ (function () {
  51898. function MeshBuilder() {
  51899. }
  51900. MeshBuilder.updateSideOrientation = function (orientation) {
  51901. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  51902. return BABYLON.Mesh.DOUBLESIDE;
  51903. }
  51904. if (orientation === undefined || orientation === null) {
  51905. return BABYLON.Mesh.FRONTSIDE;
  51906. }
  51907. return orientation;
  51908. };
  51909. /**
  51910. * Creates a box mesh.
  51911. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  51912. * The parameter `size` sets the size (float) of each box side (default 1).
  51913. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  51914. * 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).
  51915. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51917. * 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).
  51918. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51920. */
  51921. MeshBuilder.CreateBox = function (name, options, scene) {
  51922. if (scene === void 0) { scene = null; }
  51923. var box = new BABYLON.Mesh(name, scene);
  51924. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51925. box._originalBuilderSideOrientation = options.sideOrientation;
  51926. var vertexData = BABYLON.VertexData.CreateBox(options);
  51927. vertexData.applyToMesh(box, options.updatable);
  51928. return box;
  51929. };
  51930. /**
  51931. * Creates a sphere mesh.
  51932. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51933. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51934. * 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`).
  51935. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51936. * 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
  51937. * 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).
  51938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51939. * 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).
  51940. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51942. */
  51943. MeshBuilder.CreateSphere = function (name, options, scene) {
  51944. var sphere = new BABYLON.Mesh(name, scene);
  51945. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51946. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51947. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51948. vertexData.applyToMesh(sphere, options.updatable);
  51949. return sphere;
  51950. };
  51951. /**
  51952. * Creates a plane polygonal mesh. By default, this is a disc.
  51953. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51954. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51955. * 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.
  51956. * 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
  51957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51958. * 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).
  51959. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51961. */
  51962. MeshBuilder.CreateDisc = function (name, options, scene) {
  51963. if (scene === void 0) { scene = null; }
  51964. var disc = new BABYLON.Mesh(name, scene);
  51965. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51966. disc._originalBuilderSideOrientation = options.sideOrientation;
  51967. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51968. vertexData.applyToMesh(disc, options.updatable);
  51969. return disc;
  51970. };
  51971. /**
  51972. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51973. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51974. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51975. * 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`).
  51976. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51977. * 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.
  51978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51979. * 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).
  51980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51982. */
  51983. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51984. var sphere = new BABYLON.Mesh(name, scene);
  51985. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51986. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51987. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51988. vertexData.applyToMesh(sphere, options.updatable);
  51989. return sphere;
  51990. };
  51991. ;
  51992. /**
  51993. * Creates a ribbon mesh.
  51994. * 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.
  51995. *
  51996. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51997. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51998. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51999. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  52000. * 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.
  52001. * 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.
  52002. * 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
  52003. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52004. * 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).
  52005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52006. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52007. * 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.
  52008. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  52009. * 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
  52010. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  52011. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  52012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52013. */
  52014. MeshBuilder.CreateRibbon = function (name, options, scene) {
  52015. if (scene === void 0) { scene = null; }
  52016. var pathArray = options.pathArray;
  52017. var closeArray = options.closeArray;
  52018. var closePath = options.closePath;
  52019. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52020. var instance = options.instance;
  52021. var updatable = options.updatable;
  52022. if (instance) {
  52023. // positionFunction : ribbon case
  52024. // only pathArray and sideOrientation parameters are taken into account for positions update
  52025. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  52026. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  52027. var positionFunction = function (positions) {
  52028. var minlg = pathArray[0].length;
  52029. var i = 0;
  52030. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  52031. for (var si = 1; si <= ns; si++) {
  52032. for (var p = 0; p < pathArray.length; p++) {
  52033. var path = pathArray[p];
  52034. var l = path.length;
  52035. minlg = (minlg < l) ? minlg : l;
  52036. var j = 0;
  52037. while (j < minlg) {
  52038. positions[i] = path[j].x;
  52039. positions[i + 1] = path[j].y;
  52040. positions[i + 2] = path[j].z;
  52041. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  52042. BABYLON.Tmp.Vector3[0].x = path[j].x;
  52043. }
  52044. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  52045. BABYLON.Tmp.Vector3[1].x = path[j].x;
  52046. }
  52047. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  52048. BABYLON.Tmp.Vector3[0].y = path[j].y;
  52049. }
  52050. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  52051. BABYLON.Tmp.Vector3[1].y = path[j].y;
  52052. }
  52053. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  52054. BABYLON.Tmp.Vector3[0].z = path[j].z;
  52055. }
  52056. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  52057. BABYLON.Tmp.Vector3[1].z = path[j].z;
  52058. }
  52059. j++;
  52060. i += 3;
  52061. }
  52062. if (instance._closePath) {
  52063. positions[i] = path[0].x;
  52064. positions[i + 1] = path[0].y;
  52065. positions[i + 2] = path[0].z;
  52066. i += 3;
  52067. }
  52068. }
  52069. }
  52070. };
  52071. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52072. positionFunction(positions);
  52073. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  52074. instance._boundingInfo.update(instance._worldMatrix);
  52075. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52076. if (options.colors) {
  52077. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52078. for (var c = 0; c < options.colors.length; c++) {
  52079. colors[c * 4] = options.colors[c].r;
  52080. colors[c * 4 + 1] = options.colors[c].g;
  52081. colors[c * 4 + 2] = options.colors[c].b;
  52082. colors[c * 4 + 3] = options.colors[c].a;
  52083. }
  52084. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  52085. }
  52086. if (options.uvs) {
  52087. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52088. for (var i = 0; i < options.uvs.length; i++) {
  52089. uvs[i * 2] = options.uvs[i].x;
  52090. uvs[i * 2 + 1] = options.uvs[i].y;
  52091. }
  52092. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  52093. }
  52094. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  52095. var indices = instance.getIndices();
  52096. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52097. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  52098. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  52099. if (instance._closePath) {
  52100. var indexFirst = 0;
  52101. var indexLast = 0;
  52102. for (var p = 0; p < pathArray.length; p++) {
  52103. indexFirst = instance._idx[p] * 3;
  52104. if (p + 1 < pathArray.length) {
  52105. indexLast = (instance._idx[p + 1] - 1) * 3;
  52106. }
  52107. else {
  52108. indexLast = normals.length - 3;
  52109. }
  52110. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  52111. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  52112. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  52113. normals[indexLast] = normals[indexFirst];
  52114. normals[indexLast + 1] = normals[indexFirst + 1];
  52115. normals[indexLast + 2] = normals[indexFirst + 2];
  52116. }
  52117. }
  52118. if (!(instance.areNormalsFrozen)) {
  52119. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  52120. }
  52121. }
  52122. return instance;
  52123. }
  52124. else {
  52125. var ribbon = new BABYLON.Mesh(name, scene);
  52126. ribbon._originalBuilderSideOrientation = sideOrientation;
  52127. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  52128. if (closePath) {
  52129. ribbon._idx = vertexData._idx;
  52130. }
  52131. ribbon._closePath = closePath;
  52132. ribbon._closeArray = closeArray;
  52133. vertexData.applyToMesh(ribbon, updatable);
  52134. return ribbon;
  52135. }
  52136. };
  52137. /**
  52138. * Creates a cylinder or a cone mesh.
  52139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  52140. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  52141. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  52142. * 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.
  52143. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  52144. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  52145. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  52146. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  52147. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  52148. * 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).
  52149. * 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
  52150. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  52151. * 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
  52152. * 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.
  52153. * If `enclose` is false, a ring surface is one element.
  52154. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  52155. * 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
  52156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52157. * 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).
  52158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52160. */
  52161. MeshBuilder.CreateCylinder = function (name, options, scene) {
  52162. var cylinder = new BABYLON.Mesh(name, scene);
  52163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52164. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  52165. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  52166. vertexData.applyToMesh(cylinder, options.updatable);
  52167. return cylinder;
  52168. };
  52169. /**
  52170. * Creates a torus mesh.
  52171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  52172. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  52173. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  52174. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  52175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52176. * 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).
  52177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52179. */
  52180. MeshBuilder.CreateTorus = function (name, options, scene) {
  52181. var torus = new BABYLON.Mesh(name, scene);
  52182. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52183. torus._originalBuilderSideOrientation = options.sideOrientation;
  52184. var vertexData = BABYLON.VertexData.CreateTorus(options);
  52185. vertexData.applyToMesh(torus, options.updatable);
  52186. return torus;
  52187. };
  52188. /**
  52189. * Creates a torus knot mesh.
  52190. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  52191. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  52192. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  52193. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  52194. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  52195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52196. * 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).
  52197. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52198. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52199. */
  52200. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  52201. var torusKnot = new BABYLON.Mesh(name, scene);
  52202. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52203. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  52204. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  52205. vertexData.applyToMesh(torusKnot, options.updatable);
  52206. return torusKnot;
  52207. };
  52208. /**
  52209. * Creates a line system mesh.
  52210. * A line system is a pool of many lines gathered in a single mesh.
  52211. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  52212. * 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.
  52213. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  52214. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  52215. * 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
  52216. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  52217. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  52218. * 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
  52219. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  52220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52221. */
  52222. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  52223. var instance = options.instance;
  52224. var lines = options.lines;
  52225. var colors = options.colors;
  52226. if (instance) {
  52227. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52228. var vertexColor;
  52229. var lineColors;
  52230. if (colors) {
  52231. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52232. }
  52233. var i = 0;
  52234. var c = 0;
  52235. for (var l = 0; l < lines.length; l++) {
  52236. var points = lines[l];
  52237. for (var p = 0; p < points.length; p++) {
  52238. positions[i] = points[p].x;
  52239. positions[i + 1] = points[p].y;
  52240. positions[i + 2] = points[p].z;
  52241. if (colors && vertexColor) {
  52242. lineColors = colors[l];
  52243. vertexColor[c] = lineColors[p].r;
  52244. vertexColor[c + 1] = lineColors[p].g;
  52245. vertexColor[c + 2] = lineColors[p].b;
  52246. vertexColor[c + 3] = lineColors[p].a;
  52247. c += 4;
  52248. }
  52249. i += 3;
  52250. }
  52251. }
  52252. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52253. if (colors && vertexColor) {
  52254. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  52255. }
  52256. return instance;
  52257. }
  52258. // line system creation
  52259. var useVertexColor = (colors) ? true : false;
  52260. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  52261. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  52262. vertexData.applyToMesh(lineSystem, options.updatable);
  52263. return lineSystem;
  52264. };
  52265. /**
  52266. * Creates a line mesh.
  52267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  52268. * 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.
  52269. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52270. * The parameter `points` is an array successive Vector3.
  52271. * 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
  52272. * The optional parameter `colors` is an array of successive Color4, one per line point.
  52273. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  52274. * When updating an instance, remember that only point positions can change, not the number of points.
  52275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52276. */
  52277. MeshBuilder.CreateLines = function (name, options, scene) {
  52278. if (scene === void 0) { scene = null; }
  52279. var colors = (options.colors) ? [options.colors] : null;
  52280. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  52281. return lines;
  52282. };
  52283. /**
  52284. * Creates a dashed line mesh.
  52285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  52286. * 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.
  52287. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52288. * The parameter `points` is an array successive Vector3.
  52289. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  52290. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  52291. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  52292. * 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
  52293. * When updating an instance, remember that only point positions can change, not the number of points.
  52294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52295. */
  52296. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  52297. if (scene === void 0) { scene = null; }
  52298. var points = options.points;
  52299. var instance = options.instance;
  52300. var gapSize = options.gapSize || 1;
  52301. var dashSize = options.dashSize || 3;
  52302. if (instance) {
  52303. var positionFunction = function (positions) {
  52304. var curvect = BABYLON.Vector3.Zero();
  52305. var nbSeg = positions.length / 6;
  52306. var lg = 0;
  52307. var nb = 0;
  52308. var shft = 0;
  52309. var dashshft = 0;
  52310. var curshft = 0;
  52311. var p = 0;
  52312. var i = 0;
  52313. var j = 0;
  52314. for (i = 0; i < points.length - 1; i++) {
  52315. points[i + 1].subtractToRef(points[i], curvect);
  52316. lg += curvect.length();
  52317. }
  52318. shft = lg / nbSeg;
  52319. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  52320. for (i = 0; i < points.length - 1; i++) {
  52321. points[i + 1].subtractToRef(points[i], curvect);
  52322. nb = Math.floor(curvect.length() / shft);
  52323. curvect.normalize();
  52324. j = 0;
  52325. while (j < nb && p < positions.length) {
  52326. curshft = shft * j;
  52327. positions[p] = points[i].x + curshft * curvect.x;
  52328. positions[p + 1] = points[i].y + curshft * curvect.y;
  52329. positions[p + 2] = points[i].z + curshft * curvect.z;
  52330. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  52331. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  52332. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  52333. p += 6;
  52334. j++;
  52335. }
  52336. }
  52337. while (p < positions.length) {
  52338. positions[p] = points[i].x;
  52339. positions[p + 1] = points[i].y;
  52340. positions[p + 2] = points[i].z;
  52341. p += 3;
  52342. }
  52343. };
  52344. instance.updateMeshPositions(positionFunction, false);
  52345. return instance;
  52346. }
  52347. // dashed lines creation
  52348. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52349. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52350. vertexData.applyToMesh(dashedLines, options.updatable);
  52351. dashedLines.dashSize = dashSize;
  52352. dashedLines.gapSize = gapSize;
  52353. return dashedLines;
  52354. };
  52355. /**
  52356. * Creates an extruded shape mesh.
  52357. * 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.
  52358. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52359. *
  52360. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52361. * 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
  52362. * extruded along the Z axis.
  52363. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52364. * 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.
  52365. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52366. * 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
  52367. * 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
  52368. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52370. * 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).
  52371. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52372. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52374. */
  52375. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52376. if (scene === void 0) { scene = null; }
  52377. var path = options.path;
  52378. var shape = options.shape;
  52379. var scale = options.scale || 1;
  52380. var rotation = options.rotation || 0;
  52381. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52382. var updatable = options.updatable;
  52383. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52384. var instance = options.instance || null;
  52385. var invertUV = options.invertUV || false;
  52386. 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);
  52387. };
  52388. /**
  52389. * Creates an custom extruded shape mesh.
  52390. * 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.
  52391. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52392. *
  52393. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52394. * 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
  52395. * extruded along the Z axis.
  52396. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52397. * 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
  52398. * and the distance of this point from the begining of the path :
  52399. * ```javascript
  52400. * var rotationFunction = function(i, distance) {
  52401. * // do things
  52402. * return rotationValue; }
  52403. * ```
  52404. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52405. * 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
  52406. * and the distance of this point from the begining of the path :
  52407. * ```javascript
  52408. * var scaleFunction = function(i, distance) {
  52409. * // do things
  52410. * return scaleValue;}
  52411. * ```
  52412. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52413. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52414. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52415. * 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
  52416. * 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
  52417. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52419. * 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).
  52420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52421. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52423. */
  52424. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52425. var path = options.path;
  52426. var shape = options.shape;
  52427. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52428. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52429. var ribbonCloseArray = options.ribbonCloseArray || false;
  52430. var ribbonClosePath = options.ribbonClosePath || false;
  52431. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52432. var updatable = options.updatable;
  52433. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52434. var instance = options.instance;
  52435. var invertUV = options.invertUV || false;
  52436. 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);
  52437. };
  52438. /**
  52439. * Creates lathe mesh.
  52440. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52441. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52442. *
  52443. * 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
  52444. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52445. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52446. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52447. * 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.
  52448. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52449. * 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
  52450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52451. * 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).
  52452. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52453. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52455. */
  52456. MeshBuilder.CreateLathe = function (name, options, scene) {
  52457. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52458. var closed = (options.closed === undefined) ? true : options.closed;
  52459. var shape = options.shape;
  52460. var radius = options.radius || 1;
  52461. var tessellation = options.tessellation || 64;
  52462. var updatable = options.updatable;
  52463. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52464. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52465. var pi2 = Math.PI * 2;
  52466. var paths = new Array();
  52467. var invertUV = options.invertUV || false;
  52468. var i = 0;
  52469. var p = 0;
  52470. var step = pi2 / tessellation * arc;
  52471. var rotated;
  52472. var path = new Array();
  52473. ;
  52474. for (i = 0; i <= tessellation; i++) {
  52475. var path = [];
  52476. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52477. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52478. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52479. }
  52480. for (p = 0; p < shape.length; p++) {
  52481. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52482. path.push(rotated);
  52483. }
  52484. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52485. 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));
  52486. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52487. }
  52488. paths.push(path);
  52489. }
  52490. // lathe ribbon
  52491. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52492. return lathe;
  52493. };
  52494. /**
  52495. * Creates a plane mesh.
  52496. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52497. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52498. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52499. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52500. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52501. * 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).
  52502. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52504. */
  52505. MeshBuilder.CreatePlane = function (name, options, scene) {
  52506. var plane = new BABYLON.Mesh(name, scene);
  52507. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52508. plane._originalBuilderSideOrientation = options.sideOrientation;
  52509. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52510. vertexData.applyToMesh(plane, options.updatable);
  52511. if (options.sourcePlane) {
  52512. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52513. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52514. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52515. plane.rotate(vectorProduct, product);
  52516. }
  52517. return plane;
  52518. };
  52519. /**
  52520. * Creates a ground mesh.
  52521. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52522. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52523. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52524. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52525. */
  52526. MeshBuilder.CreateGround = function (name, options, scene) {
  52527. var ground = new BABYLON.GroundMesh(name, scene);
  52528. ground._setReady(false);
  52529. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52530. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52531. ground._width = options.width || 1;
  52532. ground._height = options.height || 1;
  52533. ground._maxX = ground._width / 2;
  52534. ground._maxZ = ground._height / 2;
  52535. ground._minX = -ground._maxX;
  52536. ground._minZ = -ground._maxZ;
  52537. var vertexData = BABYLON.VertexData.CreateGround(options);
  52538. vertexData.applyToMesh(ground, options.updatable);
  52539. ground._setReady(true);
  52540. return ground;
  52541. };
  52542. /**
  52543. * Creates a tiled ground mesh.
  52544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52545. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52546. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52547. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52548. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52549. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52550. * numbers of subdivisions on the ground width and height of each tile.
  52551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52552. */
  52553. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52554. var tiledGround = new BABYLON.Mesh(name, scene);
  52555. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52556. vertexData.applyToMesh(tiledGround, options.updatable);
  52557. return tiledGround;
  52558. };
  52559. /**
  52560. * Creates a ground mesh from a height map.
  52561. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52563. * The parameter `url` sets the URL of the height map image resource.
  52564. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52565. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52566. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52567. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52568. * 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.
  52569. * 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).
  52570. * This function is passed the newly built mesh :
  52571. * ```javascript
  52572. * function(mesh) { // do things
  52573. * return; }
  52574. * ```
  52575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52576. */
  52577. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52578. var width = options.width || 10.0;
  52579. var height = options.height || 10.0;
  52580. var subdivisions = options.subdivisions || 1 | 0;
  52581. var minHeight = options.minHeight || 0.0;
  52582. var maxHeight = options.maxHeight || 1.0;
  52583. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52584. var updatable = options.updatable;
  52585. var onReady = options.onReady;
  52586. var ground = new BABYLON.GroundMesh(name, scene);
  52587. ground._subdivisionsX = subdivisions;
  52588. ground._subdivisionsY = subdivisions;
  52589. ground._width = width;
  52590. ground._height = height;
  52591. ground._maxX = ground._width / 2.0;
  52592. ground._maxZ = ground._height / 2.0;
  52593. ground._minX = -ground._maxX;
  52594. ground._minZ = -ground._maxZ;
  52595. ground._setReady(false);
  52596. var onload = function (img) {
  52597. // Getting height map data
  52598. var canvas = document.createElement("canvas");
  52599. var context = canvas.getContext("2d");
  52600. if (!context) {
  52601. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52602. }
  52603. if (scene.isDisposed) {
  52604. return;
  52605. }
  52606. var bufferWidth = img.width;
  52607. var bufferHeight = img.height;
  52608. canvas.width = bufferWidth;
  52609. canvas.height = bufferHeight;
  52610. context.drawImage(img, 0, 0);
  52611. // Create VertexData from map data
  52612. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52613. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52614. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52615. width: width, height: height,
  52616. subdivisions: subdivisions,
  52617. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52618. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52619. });
  52620. vertexData.applyToMesh(ground, updatable);
  52621. ground._setReady(true);
  52622. //execute ready callback, if set
  52623. if (onReady) {
  52624. onReady(ground);
  52625. }
  52626. };
  52627. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52628. return ground;
  52629. };
  52630. /**
  52631. * Creates a polygon mesh.
  52632. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52633. * 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.
  52634. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52635. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52636. * 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).
  52637. * Remember you can only change the shape positions, not their number when updating a polygon.
  52638. */
  52639. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52640. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52641. var shape = options.shape;
  52642. var holes = options.holes || [];
  52643. var depth = options.depth || 0;
  52644. var contours = [];
  52645. var hole = [];
  52646. for (var i = 0; i < shape.length; i++) {
  52647. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52648. }
  52649. var epsilon = 0.00000001;
  52650. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52651. contours.pop();
  52652. }
  52653. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52654. for (var hNb = 0; hNb < holes.length; hNb++) {
  52655. hole = [];
  52656. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52657. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52658. }
  52659. polygonTriangulation.addHole(hole);
  52660. }
  52661. var polygon = polygonTriangulation.build(options.updatable, depth);
  52662. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52663. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52664. vertexData.applyToMesh(polygon, options.updatable);
  52665. return polygon;
  52666. };
  52667. ;
  52668. /**
  52669. * Creates an extruded polygon mesh, with depth in the Y direction.
  52670. * 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).
  52671. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52672. */
  52673. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52674. return MeshBuilder.CreatePolygon(name, options, scene);
  52675. };
  52676. ;
  52677. /**
  52678. * Creates a tube mesh.
  52679. * 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.
  52680. *
  52681. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52682. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52683. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52684. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52685. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52686. * 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.
  52687. * It must return a radius value (positive float) :
  52688. * ```javascript
  52689. * var radiusFunction = function(i, distance) {
  52690. * // do things
  52691. * return radius; }
  52692. * ```
  52693. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52694. * 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
  52695. * 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
  52696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52697. * 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).
  52698. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52699. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52701. */
  52702. MeshBuilder.CreateTube = function (name, options, scene) {
  52703. var path = options.path;
  52704. var instance = options.instance;
  52705. var radius = 1.0;
  52706. if (instance) {
  52707. radius = instance.radius;
  52708. }
  52709. if (options.radius !== undefined) {
  52710. radius = options.radius;
  52711. }
  52712. ;
  52713. var tessellation = options.tessellation || 64 | 0;
  52714. var radiusFunction = options.radiusFunction || null;
  52715. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52716. var invertUV = options.invertUV || false;
  52717. var updatable = options.updatable;
  52718. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52719. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52720. // tube geometry
  52721. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52722. var tangents = path3D.getTangents();
  52723. var normals = path3D.getNormals();
  52724. var distances = path3D.getDistances();
  52725. var pi2 = Math.PI * 2;
  52726. var step = pi2 / tessellation * arc;
  52727. var returnRadius = function () { return radius; };
  52728. var radiusFunctionFinal = radiusFunction || returnRadius;
  52729. var circlePath;
  52730. var rad;
  52731. var normal;
  52732. var rotated;
  52733. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52734. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52735. for (var i = 0; i < path.length; i++) {
  52736. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52737. circlePath = Array(); // current circle array
  52738. normal = normals[i]; // current normal
  52739. for (var t = 0; t < tessellation; t++) {
  52740. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52741. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52742. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52743. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52744. circlePath[t] = rotated;
  52745. }
  52746. circlePaths[index] = circlePath;
  52747. index++;
  52748. }
  52749. // cap
  52750. var capPath = function (nbPoints, pathIndex) {
  52751. var pointCap = Array();
  52752. for (var i = 0; i < nbPoints; i++) {
  52753. pointCap.push(path[pathIndex]);
  52754. }
  52755. return pointCap;
  52756. };
  52757. switch (cap) {
  52758. case BABYLON.Mesh.NO_CAP:
  52759. break;
  52760. case BABYLON.Mesh.CAP_START:
  52761. circlePaths[0] = capPath(tessellation, 0);
  52762. circlePaths[1] = circlePaths[2].slice(0);
  52763. break;
  52764. case BABYLON.Mesh.CAP_END:
  52765. circlePaths[index] = circlePaths[index - 1].slice(0);
  52766. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52767. break;
  52768. case BABYLON.Mesh.CAP_ALL:
  52769. circlePaths[0] = capPath(tessellation, 0);
  52770. circlePaths[1] = circlePaths[2].slice(0);
  52771. circlePaths[index] = circlePaths[index - 1].slice(0);
  52772. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52773. break;
  52774. default:
  52775. break;
  52776. }
  52777. return circlePaths;
  52778. };
  52779. var path3D;
  52780. var pathArray;
  52781. if (instance) {
  52782. var arc = options.arc || instance.arc;
  52783. path3D = (instance.path3D).update(path);
  52784. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52785. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52786. instance.path3D = path3D;
  52787. instance.pathArray = pathArray;
  52788. instance.arc = arc;
  52789. instance.radius = radius;
  52790. return instance;
  52791. }
  52792. // tube creation
  52793. path3D = new BABYLON.Path3D(path);
  52794. var newPathArray = new Array();
  52795. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52796. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52797. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52798. tube.pathArray = pathArray;
  52799. tube.path3D = path3D;
  52800. tube.tessellation = tessellation;
  52801. tube.cap = cap;
  52802. tube.arc = options.arc;
  52803. tube.radius = radius;
  52804. return tube;
  52805. };
  52806. /**
  52807. * Creates a polyhedron mesh.
  52808. *
  52809. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  52810. * 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
  52811. * to choose the wanted type.
  52812. * The parameter `size` (positive float, default 1) sets the polygon size.
  52813. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  52814. * 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`.
  52815. * 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
  52816. * 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)`).
  52817. * 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
  52818. * 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.
  52819. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52820. * 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).
  52821. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52823. */
  52824. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  52825. var polyhedron = new BABYLON.Mesh(name, scene);
  52826. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52827. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  52828. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  52829. vertexData.applyToMesh(polyhedron, options.updatable);
  52830. return polyhedron;
  52831. };
  52832. /**
  52833. * Creates a decal mesh.
  52834. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  52835. * 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.
  52836. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  52837. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  52838. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  52839. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  52840. */
  52841. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  52842. var indices = sourceMesh.getIndices();
  52843. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52844. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52845. var position = options.position || BABYLON.Vector3.Zero();
  52846. var normal = options.normal || BABYLON.Vector3.Up();
  52847. var size = options.size || BABYLON.Vector3.One();
  52848. var angle = options.angle || 0;
  52849. // Getting correct rotation
  52850. if (!normal) {
  52851. var target = new BABYLON.Vector3(0, 0, 1);
  52852. var camera = sourceMesh.getScene().activeCamera;
  52853. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  52854. normal = camera.globalPosition.subtract(cameraWorldTarget);
  52855. }
  52856. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  52857. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  52858. var pitch = Math.atan2(normal.y, len);
  52859. // Matrix
  52860. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  52861. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  52862. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  52863. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  52864. var vertexData = new BABYLON.VertexData();
  52865. vertexData.indices = [];
  52866. vertexData.positions = [];
  52867. vertexData.normals = [];
  52868. vertexData.uvs = [];
  52869. var currentVertexDataIndex = 0;
  52870. var extractDecalVector3 = function (indexId) {
  52871. var result = new BABYLON.PositionNormalVertex();
  52872. if (!indices || !positions || !normals) {
  52873. return result;
  52874. }
  52875. var vertexId = indices[indexId];
  52876. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  52877. // Send vector to decal local world
  52878. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  52879. // Get normal
  52880. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  52881. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  52882. return result;
  52883. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  52884. var clip = function (vertices, axis) {
  52885. if (vertices.length === 0) {
  52886. return vertices;
  52887. }
  52888. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  52889. var clipVertices = function (v0, v1) {
  52890. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  52891. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  52892. };
  52893. var result = new Array();
  52894. for (var index = 0; index < vertices.length; index += 3) {
  52895. var v1Out;
  52896. var v2Out;
  52897. var v3Out;
  52898. var total = 0;
  52899. var nV1 = null;
  52900. var nV2 = null;
  52901. var nV3 = null;
  52902. var nV4 = null;
  52903. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  52904. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  52905. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  52906. v1Out = d1 > 0;
  52907. v2Out = d2 > 0;
  52908. v3Out = d3 > 0;
  52909. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  52910. switch (total) {
  52911. case 0:
  52912. result.push(vertices[index]);
  52913. result.push(vertices[index + 1]);
  52914. result.push(vertices[index + 2]);
  52915. break;
  52916. case 1:
  52917. if (v1Out) {
  52918. nV1 = vertices[index + 1];
  52919. nV2 = vertices[index + 2];
  52920. nV3 = clipVertices(vertices[index], nV1);
  52921. nV4 = clipVertices(vertices[index], nV2);
  52922. }
  52923. if (v2Out) {
  52924. nV1 = vertices[index];
  52925. nV2 = vertices[index + 2];
  52926. nV3 = clipVertices(vertices[index + 1], nV1);
  52927. nV4 = clipVertices(vertices[index + 1], nV2);
  52928. result.push(nV3);
  52929. result.push(nV2.clone());
  52930. result.push(nV1.clone());
  52931. result.push(nV2.clone());
  52932. result.push(nV3.clone());
  52933. result.push(nV4);
  52934. break;
  52935. }
  52936. if (v3Out) {
  52937. nV1 = vertices[index];
  52938. nV2 = vertices[index + 1];
  52939. nV3 = clipVertices(vertices[index + 2], nV1);
  52940. nV4 = clipVertices(vertices[index + 2], nV2);
  52941. }
  52942. if (nV1 && nV2 && nV3 && nV4) {
  52943. result.push(nV1.clone());
  52944. result.push(nV2.clone());
  52945. result.push(nV3);
  52946. result.push(nV4);
  52947. result.push(nV3.clone());
  52948. result.push(nV2.clone());
  52949. }
  52950. break;
  52951. case 2:
  52952. if (!v1Out) {
  52953. nV1 = vertices[index].clone();
  52954. nV2 = clipVertices(nV1, vertices[index + 1]);
  52955. nV3 = clipVertices(nV1, vertices[index + 2]);
  52956. result.push(nV1);
  52957. result.push(nV2);
  52958. result.push(nV3);
  52959. }
  52960. if (!v2Out) {
  52961. nV1 = vertices[index + 1].clone();
  52962. nV2 = clipVertices(nV1, vertices[index + 2]);
  52963. nV3 = clipVertices(nV1, vertices[index]);
  52964. result.push(nV1);
  52965. result.push(nV2);
  52966. result.push(nV3);
  52967. }
  52968. if (!v3Out) {
  52969. nV1 = vertices[index + 2].clone();
  52970. nV2 = clipVertices(nV1, vertices[index]);
  52971. nV3 = clipVertices(nV1, vertices[index + 1]);
  52972. result.push(nV1);
  52973. result.push(nV2);
  52974. result.push(nV3);
  52975. }
  52976. break;
  52977. case 3:
  52978. break;
  52979. }
  52980. }
  52981. return result;
  52982. };
  52983. for (var index = 0; index < indices.length; index += 3) {
  52984. var faceVertices = new Array();
  52985. faceVertices.push(extractDecalVector3(index));
  52986. faceVertices.push(extractDecalVector3(index + 1));
  52987. faceVertices.push(extractDecalVector3(index + 2));
  52988. // Clip
  52989. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52990. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52991. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52992. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52993. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52994. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52995. if (faceVertices.length === 0) {
  52996. continue;
  52997. }
  52998. // Add UVs and get back to world
  52999. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  53000. var vertex = faceVertices[vIndex];
  53001. //TODO check for Int32Array | Uint32Array | Uint16Array
  53002. vertexData.indices.push(currentVertexDataIndex);
  53003. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  53004. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  53005. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  53006. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  53007. currentVertexDataIndex++;
  53008. }
  53009. }
  53010. // Return mesh
  53011. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  53012. vertexData.applyToMesh(decal);
  53013. decal.position = position.clone();
  53014. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  53015. return decal;
  53016. };
  53017. // Privates
  53018. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  53019. // extrusion geometry
  53020. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  53021. var tangents = path3D.getTangents();
  53022. var normals = path3D.getNormals();
  53023. var binormals = path3D.getBinormals();
  53024. var distances = path3D.getDistances();
  53025. var angle = 0;
  53026. var returnScale = function () { return scale !== null ? scale : 1; };
  53027. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  53028. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  53029. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  53030. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53031. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53032. for (var i = 0; i < curve.length; i++) {
  53033. var shapePath = new Array();
  53034. var angleStep = rotate(i, distances[i]);
  53035. var scaleRatio = scl(i, distances[i]);
  53036. for (var p = 0; p < shape.length; p++) {
  53037. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  53038. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  53039. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  53040. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  53041. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  53042. shapePath[p] = rotated;
  53043. }
  53044. shapePaths[index] = shapePath;
  53045. angle += angleStep;
  53046. index++;
  53047. }
  53048. // cap
  53049. var capPath = function (shapePath) {
  53050. var pointCap = Array();
  53051. var barycenter = BABYLON.Vector3.Zero();
  53052. var i;
  53053. for (i = 0; i < shapePath.length; i++) {
  53054. barycenter.addInPlace(shapePath[i]);
  53055. }
  53056. barycenter.scaleInPlace(1.0 / shapePath.length);
  53057. for (i = 0; i < shapePath.length; i++) {
  53058. pointCap.push(barycenter);
  53059. }
  53060. return pointCap;
  53061. };
  53062. switch (cap) {
  53063. case BABYLON.Mesh.NO_CAP:
  53064. break;
  53065. case BABYLON.Mesh.CAP_START:
  53066. shapePaths[0] = capPath(shapePaths[2]);
  53067. shapePaths[1] = shapePaths[2];
  53068. break;
  53069. case BABYLON.Mesh.CAP_END:
  53070. shapePaths[index] = shapePaths[index - 1];
  53071. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53072. break;
  53073. case BABYLON.Mesh.CAP_ALL:
  53074. shapePaths[0] = capPath(shapePaths[2]);
  53075. shapePaths[1] = shapePaths[2];
  53076. shapePaths[index] = shapePaths[index - 1];
  53077. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53078. break;
  53079. default:
  53080. break;
  53081. }
  53082. return shapePaths;
  53083. };
  53084. var path3D;
  53085. var pathArray;
  53086. if (instance) {
  53087. path3D = (instance.path3D).update(curve);
  53088. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  53089. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  53090. return instance;
  53091. }
  53092. // extruded shape creation
  53093. path3D = new BABYLON.Path3D(curve);
  53094. var newShapePaths = new Array();
  53095. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53096. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  53097. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  53098. extrudedGeneric.pathArray = pathArray;
  53099. extrudedGeneric.path3D = path3D;
  53100. extrudedGeneric.cap = cap;
  53101. return extrudedGeneric;
  53102. };
  53103. return MeshBuilder;
  53104. }());
  53105. BABYLON.MeshBuilder = MeshBuilder;
  53106. })(BABYLON || (BABYLON = {}));
  53107. //# sourceMappingURL=babylon.meshBuilder.js.map
  53108. var BABYLON;
  53109. (function (BABYLON) {
  53110. var AudioEngine = /** @class */ (function () {
  53111. function AudioEngine() {
  53112. this._audioContext = null;
  53113. this._audioContextInitialized = false;
  53114. this.canUseWebAudio = false;
  53115. this.WarnedWebAudioUnsupported = false;
  53116. this.unlocked = false;
  53117. this.isMP3supported = false;
  53118. this.isOGGsupported = false;
  53119. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  53120. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  53121. this.canUseWebAudio = true;
  53122. }
  53123. var audioElem = document.createElement('audio');
  53124. try {
  53125. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  53126. this.isMP3supported = true;
  53127. }
  53128. }
  53129. catch (e) {
  53130. // protect error during capability check.
  53131. }
  53132. try {
  53133. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  53134. this.isOGGsupported = true;
  53135. }
  53136. }
  53137. catch (e) {
  53138. // protect error during capability check.
  53139. }
  53140. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  53141. this._unlockiOSaudio();
  53142. }
  53143. else {
  53144. this.unlocked = true;
  53145. }
  53146. }
  53147. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  53148. get: function () {
  53149. if (!this._audioContextInitialized) {
  53150. this._initializeAudioContext();
  53151. }
  53152. return this._audioContext;
  53153. },
  53154. enumerable: true,
  53155. configurable: true
  53156. });
  53157. AudioEngine.prototype._unlockiOSaudio = function () {
  53158. var _this = this;
  53159. var unlockaudio = function () {
  53160. if (!_this.audioContext) {
  53161. return;
  53162. }
  53163. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  53164. var source = _this.audioContext.createBufferSource();
  53165. source.buffer = buffer;
  53166. source.connect(_this.audioContext.destination);
  53167. source.start(0);
  53168. setTimeout(function () {
  53169. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  53170. _this.unlocked = true;
  53171. window.removeEventListener('touchend', unlockaudio, false);
  53172. if (_this.onAudioUnlocked) {
  53173. _this.onAudioUnlocked();
  53174. }
  53175. }
  53176. }, 0);
  53177. };
  53178. window.addEventListener('touchend', unlockaudio, false);
  53179. };
  53180. AudioEngine.prototype._initializeAudioContext = function () {
  53181. try {
  53182. if (this.canUseWebAudio) {
  53183. this._audioContext = new AudioContext();
  53184. // create a global volume gain node
  53185. this.masterGain = this._audioContext.createGain();
  53186. this.masterGain.gain.value = 1;
  53187. this.masterGain.connect(this._audioContext.destination);
  53188. this._audioContextInitialized = true;
  53189. }
  53190. }
  53191. catch (e) {
  53192. this.canUseWebAudio = false;
  53193. BABYLON.Tools.Error("Web Audio: " + e.message);
  53194. }
  53195. };
  53196. AudioEngine.prototype.dispose = function () {
  53197. if (this.canUseWebAudio && this._audioContextInitialized) {
  53198. if (this._connectedAnalyser && this._audioContext) {
  53199. this._connectedAnalyser.stopDebugCanvas();
  53200. this._connectedAnalyser.dispose();
  53201. this.masterGain.disconnect();
  53202. this.masterGain.connect(this._audioContext.destination);
  53203. this._connectedAnalyser = null;
  53204. }
  53205. this.masterGain.gain.value = 1;
  53206. }
  53207. this.WarnedWebAudioUnsupported = false;
  53208. };
  53209. AudioEngine.prototype.getGlobalVolume = function () {
  53210. if (this.canUseWebAudio && this._audioContextInitialized) {
  53211. return this.masterGain.gain.value;
  53212. }
  53213. else {
  53214. return -1;
  53215. }
  53216. };
  53217. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  53218. if (this.canUseWebAudio && this._audioContextInitialized) {
  53219. this.masterGain.gain.value = newVolume;
  53220. }
  53221. };
  53222. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  53223. if (this._connectedAnalyser) {
  53224. this._connectedAnalyser.stopDebugCanvas();
  53225. }
  53226. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  53227. this._connectedAnalyser = analyser;
  53228. this.masterGain.disconnect();
  53229. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  53230. }
  53231. };
  53232. return AudioEngine;
  53233. }());
  53234. BABYLON.AudioEngine = AudioEngine;
  53235. })(BABYLON || (BABYLON = {}));
  53236. //# sourceMappingURL=babylon.audioEngine.js.map
  53237. var BABYLON;
  53238. (function (BABYLON) {
  53239. var Sound = /** @class */ (function () {
  53240. /**
  53241. * Create a sound and attach it to a scene
  53242. * @param name Name of your sound
  53243. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  53244. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  53245. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53246. */
  53247. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  53248. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  53249. var _this = this;
  53250. this.autoplay = false;
  53251. this.loop = false;
  53252. this.useCustomAttenuation = false;
  53253. this.spatialSound = false;
  53254. this.refDistance = 1;
  53255. this.rolloffFactor = 1;
  53256. this.maxDistance = 100;
  53257. this.distanceModel = "linear";
  53258. this._panningModel = "equalpower";
  53259. this._playbackRate = 1;
  53260. this._streaming = false;
  53261. this._startTime = 0;
  53262. this._startOffset = 0;
  53263. this._position = BABYLON.Vector3.Zero();
  53264. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  53265. this._volume = 1;
  53266. this._isReadyToPlay = false;
  53267. this.isPlaying = false;
  53268. this.isPaused = false;
  53269. this._isDirectional = false;
  53270. // Used if you'd like to create a directional sound.
  53271. // If not set, the sound will be omnidirectional
  53272. this._coneInnerAngle = 360;
  53273. this._coneOuterAngle = 360;
  53274. this._coneOuterGain = 0;
  53275. this._isOutputConnected = false;
  53276. this._urlType = "Unknown";
  53277. this.name = name;
  53278. this._scene = scene;
  53279. this._readyToPlayCallback = readyToPlayCallback;
  53280. // Default custom attenuation function is a linear attenuation
  53281. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  53282. if (currentDistance < maxDistance) {
  53283. return currentVolume * (1 - currentDistance / maxDistance);
  53284. }
  53285. else {
  53286. return 0;
  53287. }
  53288. };
  53289. if (options) {
  53290. this.autoplay = options.autoplay || false;
  53291. this.loop = options.loop || false;
  53292. // if volume === 0, we need another way to check this option
  53293. if (options.volume !== undefined) {
  53294. this._volume = options.volume;
  53295. }
  53296. this.spatialSound = options.spatialSound || false;
  53297. this.maxDistance = options.maxDistance || 100;
  53298. this.useCustomAttenuation = options.useCustomAttenuation || false;
  53299. this.rolloffFactor = options.rolloffFactor || 1;
  53300. this.refDistance = options.refDistance || 1;
  53301. this.distanceModel = options.distanceModel || "linear";
  53302. this._playbackRate = options.playbackRate || 1;
  53303. this._streaming = options.streaming || false;
  53304. }
  53305. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53306. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  53307. this._soundGain.gain.value = this._volume;
  53308. this._inputAudioNode = this._soundGain;
  53309. this._ouputAudioNode = this._soundGain;
  53310. if (this.spatialSound) {
  53311. this._createSpatialParameters();
  53312. }
  53313. this._scene.mainSoundTrack.AddSound(this);
  53314. var validParameter = true;
  53315. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  53316. if (urlOrArrayBuffer) {
  53317. if (typeof (urlOrArrayBuffer) === "string")
  53318. this._urlType = "String";
  53319. if (Array.isArray(urlOrArrayBuffer))
  53320. this._urlType = "Array";
  53321. if (urlOrArrayBuffer instanceof ArrayBuffer)
  53322. this._urlType = "ArrayBuffer";
  53323. var urls = [];
  53324. var codecSupportedFound = false;
  53325. switch (this._urlType) {
  53326. case "ArrayBuffer":
  53327. if (urlOrArrayBuffer.byteLength > 0) {
  53328. codecSupportedFound = true;
  53329. this._soundLoaded(urlOrArrayBuffer);
  53330. }
  53331. break;
  53332. case "String":
  53333. urls.push(urlOrArrayBuffer);
  53334. case "Array":
  53335. if (urls.length === 0)
  53336. urls = urlOrArrayBuffer;
  53337. // If we found a supported format, we load it immediately and stop the loop
  53338. for (var i = 0; i < urls.length; i++) {
  53339. var url = urls[i];
  53340. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53341. codecSupportedFound = true;
  53342. }
  53343. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53344. codecSupportedFound = true;
  53345. }
  53346. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53347. codecSupportedFound = true;
  53348. }
  53349. if (url.indexOf("blob:") !== -1) {
  53350. codecSupportedFound = true;
  53351. }
  53352. if (codecSupportedFound) {
  53353. // Loading sound using XHR2
  53354. if (!this._streaming) {
  53355. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53356. }
  53357. else {
  53358. this._htmlAudioElement = new Audio(url);
  53359. this._htmlAudioElement.controls = false;
  53360. this._htmlAudioElement.loop = this.loop;
  53361. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53362. this._htmlAudioElement.preload = "auto";
  53363. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53364. _this._isReadyToPlay = true;
  53365. if (_this.autoplay) {
  53366. _this.play();
  53367. }
  53368. if (_this._readyToPlayCallback) {
  53369. _this._readyToPlayCallback();
  53370. }
  53371. });
  53372. document.body.appendChild(this._htmlAudioElement);
  53373. }
  53374. break;
  53375. }
  53376. }
  53377. break;
  53378. default:
  53379. validParameter = false;
  53380. break;
  53381. }
  53382. if (!validParameter) {
  53383. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53384. }
  53385. else {
  53386. if (!codecSupportedFound) {
  53387. this._isReadyToPlay = true;
  53388. // Simulating a ready to play event to avoid breaking code path
  53389. if (this._readyToPlayCallback) {
  53390. window.setTimeout(function () {
  53391. if (_this._readyToPlayCallback) {
  53392. _this._readyToPlayCallback();
  53393. }
  53394. }, 1000);
  53395. }
  53396. }
  53397. }
  53398. }
  53399. }
  53400. else {
  53401. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53402. this._scene.mainSoundTrack.AddSound(this);
  53403. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53404. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53405. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53406. }
  53407. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53408. if (this._readyToPlayCallback) {
  53409. window.setTimeout(function () {
  53410. if (_this._readyToPlayCallback) {
  53411. _this._readyToPlayCallback();
  53412. }
  53413. }, 1000);
  53414. }
  53415. }
  53416. }
  53417. Sound.prototype.dispose = function () {
  53418. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53419. if (this.isPlaying) {
  53420. this.stop();
  53421. }
  53422. this._isReadyToPlay = false;
  53423. if (this.soundTrackId === -1) {
  53424. this._scene.mainSoundTrack.RemoveSound(this);
  53425. }
  53426. else {
  53427. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53428. }
  53429. if (this._soundGain) {
  53430. this._soundGain.disconnect();
  53431. this._soundGain = null;
  53432. }
  53433. if (this._soundPanner) {
  53434. this._soundPanner.disconnect();
  53435. this._soundPanner = null;
  53436. }
  53437. if (this._soundSource) {
  53438. this._soundSource.disconnect();
  53439. this._soundSource = null;
  53440. }
  53441. this._audioBuffer = null;
  53442. if (this._htmlAudioElement) {
  53443. this._htmlAudioElement.pause();
  53444. this._htmlAudioElement.src = "";
  53445. document.body.removeChild(this._htmlAudioElement);
  53446. }
  53447. if (this._connectedMesh && this._registerFunc) {
  53448. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53449. this._connectedMesh = null;
  53450. }
  53451. }
  53452. };
  53453. Sound.prototype.isReady = function () {
  53454. return this._isReadyToPlay;
  53455. };
  53456. Sound.prototype._soundLoaded = function (audioData) {
  53457. var _this = this;
  53458. if (!BABYLON.Engine.audioEngine.audioContext) {
  53459. return;
  53460. }
  53461. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53462. _this._audioBuffer = buffer;
  53463. _this._isReadyToPlay = true;
  53464. if (_this.autoplay) {
  53465. _this.play();
  53466. }
  53467. if (_this._readyToPlayCallback) {
  53468. _this._readyToPlayCallback();
  53469. }
  53470. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53471. };
  53472. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53473. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53474. this._audioBuffer = audioBuffer;
  53475. this._isReadyToPlay = true;
  53476. }
  53477. };
  53478. Sound.prototype.updateOptions = function (options) {
  53479. if (options) {
  53480. this.loop = options.loop || this.loop;
  53481. this.maxDistance = options.maxDistance || this.maxDistance;
  53482. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53483. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53484. this.refDistance = options.refDistance || this.refDistance;
  53485. this.distanceModel = options.distanceModel || this.distanceModel;
  53486. this._playbackRate = options.playbackRate || this._playbackRate;
  53487. this._updateSpatialParameters();
  53488. if (this.isPlaying) {
  53489. if (this._streaming) {
  53490. this._htmlAudioElement.playbackRate = this._playbackRate;
  53491. }
  53492. else {
  53493. if (this._soundSource) {
  53494. this._soundSource.playbackRate.value = this._playbackRate;
  53495. }
  53496. }
  53497. }
  53498. }
  53499. };
  53500. Sound.prototype._createSpatialParameters = function () {
  53501. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53502. if (this._scene.headphone) {
  53503. this._panningModel = "HRTF";
  53504. }
  53505. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53506. this._updateSpatialParameters();
  53507. this._soundPanner.connect(this._ouputAudioNode);
  53508. this._inputAudioNode = this._soundPanner;
  53509. }
  53510. };
  53511. Sound.prototype._updateSpatialParameters = function () {
  53512. if (this.spatialSound && this._soundPanner) {
  53513. if (this.useCustomAttenuation) {
  53514. // Tricks to disable in a way embedded Web Audio attenuation
  53515. this._soundPanner.distanceModel = "linear";
  53516. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53517. this._soundPanner.refDistance = 1;
  53518. this._soundPanner.rolloffFactor = 1;
  53519. this._soundPanner.panningModel = this._panningModel;
  53520. }
  53521. else {
  53522. this._soundPanner.distanceModel = this.distanceModel;
  53523. this._soundPanner.maxDistance = this.maxDistance;
  53524. this._soundPanner.refDistance = this.refDistance;
  53525. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53526. this._soundPanner.panningModel = this._panningModel;
  53527. }
  53528. }
  53529. };
  53530. Sound.prototype.switchPanningModelToHRTF = function () {
  53531. this._panningModel = "HRTF";
  53532. this._switchPanningModel();
  53533. };
  53534. Sound.prototype.switchPanningModelToEqualPower = function () {
  53535. this._panningModel = "equalpower";
  53536. this._switchPanningModel();
  53537. };
  53538. Sound.prototype._switchPanningModel = function () {
  53539. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53540. this._soundPanner.panningModel = this._panningModel;
  53541. }
  53542. };
  53543. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53544. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53545. if (this._isOutputConnected) {
  53546. this._ouputAudioNode.disconnect();
  53547. }
  53548. this._ouputAudioNode.connect(soundTrackAudioNode);
  53549. this._isOutputConnected = true;
  53550. }
  53551. };
  53552. /**
  53553. * Transform this sound into a directional source
  53554. * @param coneInnerAngle Size of the inner cone in degree
  53555. * @param coneOuterAngle Size of the outer cone in degree
  53556. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53557. */
  53558. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53559. if (coneOuterAngle < coneInnerAngle) {
  53560. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53561. return;
  53562. }
  53563. this._coneInnerAngle = coneInnerAngle;
  53564. this._coneOuterAngle = coneOuterAngle;
  53565. this._coneOuterGain = coneOuterGain;
  53566. this._isDirectional = true;
  53567. if (this.isPlaying && this.loop) {
  53568. this.stop();
  53569. this.play();
  53570. }
  53571. };
  53572. Sound.prototype.setPosition = function (newPosition) {
  53573. this._position = newPosition;
  53574. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53575. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53576. }
  53577. };
  53578. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53579. this._localDirection = newLocalDirection;
  53580. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53581. this._updateDirection();
  53582. }
  53583. };
  53584. Sound.prototype._updateDirection = function () {
  53585. if (!this._connectedMesh || !this._soundPanner) {
  53586. return;
  53587. }
  53588. var mat = this._connectedMesh.getWorldMatrix();
  53589. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53590. direction.normalize();
  53591. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53592. };
  53593. Sound.prototype.updateDistanceFromListener = function () {
  53594. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53595. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53596. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53597. }
  53598. };
  53599. Sound.prototype.setAttenuationFunction = function (callback) {
  53600. this._customAttenuationFunction = callback;
  53601. };
  53602. /**
  53603. * Play the sound
  53604. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53605. * @param offset (optional) Start the sound setting it at a specific time
  53606. */
  53607. Sound.prototype.play = function (time, offset) {
  53608. var _this = this;
  53609. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53610. try {
  53611. if (this._startOffset < 0) {
  53612. time = -this._startOffset;
  53613. this._startOffset = 0;
  53614. }
  53615. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53616. if (!this._soundSource || !this._streamingSource) {
  53617. if (this.spatialSound && this._soundPanner) {
  53618. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53619. if (this._isDirectional) {
  53620. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53621. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53622. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53623. if (this._connectedMesh) {
  53624. this._updateDirection();
  53625. }
  53626. else {
  53627. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53628. }
  53629. }
  53630. }
  53631. }
  53632. if (this._streaming) {
  53633. if (!this._streamingSource) {
  53634. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53635. this._htmlAudioElement.onended = function () { _this._onended(); };
  53636. this._htmlAudioElement.playbackRate = this._playbackRate;
  53637. }
  53638. this._streamingSource.disconnect();
  53639. this._streamingSource.connect(this._inputAudioNode);
  53640. this._htmlAudioElement.play();
  53641. }
  53642. else {
  53643. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53644. this._soundSource.buffer = this._audioBuffer;
  53645. this._soundSource.connect(this._inputAudioNode);
  53646. this._soundSource.loop = this.loop;
  53647. this._soundSource.playbackRate.value = this._playbackRate;
  53648. this._soundSource.onended = function () { _this._onended(); };
  53649. if (this._soundSource.buffer) {
  53650. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53651. }
  53652. }
  53653. this._startTime = startTime;
  53654. this.isPlaying = true;
  53655. this.isPaused = false;
  53656. }
  53657. catch (ex) {
  53658. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53659. }
  53660. }
  53661. };
  53662. Sound.prototype._onended = function () {
  53663. this.isPlaying = false;
  53664. if (this.onended) {
  53665. this.onended();
  53666. }
  53667. };
  53668. /**
  53669. * Stop the sound
  53670. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53671. */
  53672. Sound.prototype.stop = function (time) {
  53673. if (this.isPlaying) {
  53674. if (this._streaming) {
  53675. this._htmlAudioElement.pause();
  53676. // Test needed for Firefox or it will generate an Invalid State Error
  53677. if (this._htmlAudioElement.currentTime > 0) {
  53678. this._htmlAudioElement.currentTime = 0;
  53679. }
  53680. }
  53681. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53682. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53683. this._soundSource.stop(stopTime);
  53684. this._soundSource.onended = function () { };
  53685. if (!this.isPaused) {
  53686. this._startOffset = 0;
  53687. }
  53688. }
  53689. this.isPlaying = false;
  53690. }
  53691. };
  53692. Sound.prototype.pause = function () {
  53693. if (this.isPlaying) {
  53694. this.isPaused = true;
  53695. if (this._streaming) {
  53696. this._htmlAudioElement.pause();
  53697. }
  53698. else if (BABYLON.Engine.audioEngine.audioContext) {
  53699. this.stop(0);
  53700. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53701. }
  53702. }
  53703. };
  53704. Sound.prototype.setVolume = function (newVolume, time) {
  53705. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53706. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53707. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53708. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53709. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53710. }
  53711. else {
  53712. this._soundGain.gain.value = newVolume;
  53713. }
  53714. }
  53715. this._volume = newVolume;
  53716. };
  53717. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53718. this._playbackRate = newPlaybackRate;
  53719. if (this.isPlaying) {
  53720. if (this._streaming) {
  53721. this._htmlAudioElement.playbackRate = this._playbackRate;
  53722. }
  53723. else if (this._soundSource) {
  53724. this._soundSource.playbackRate.value = this._playbackRate;
  53725. }
  53726. }
  53727. };
  53728. Sound.prototype.getVolume = function () {
  53729. return this._volume;
  53730. };
  53731. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53732. var _this = this;
  53733. if (this._connectedMesh && this._registerFunc) {
  53734. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53735. this._registerFunc = null;
  53736. }
  53737. this._connectedMesh = meshToConnectTo;
  53738. if (!this.spatialSound) {
  53739. this.spatialSound = true;
  53740. this._createSpatialParameters();
  53741. if (this.isPlaying && this.loop) {
  53742. this.stop();
  53743. this.play();
  53744. }
  53745. }
  53746. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53747. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53748. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53749. };
  53750. Sound.prototype.detachFromMesh = function () {
  53751. if (this._connectedMesh && this._registerFunc) {
  53752. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53753. this._registerFunc = null;
  53754. this._connectedMesh = null;
  53755. }
  53756. };
  53757. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53758. if (!node.getBoundingInfo) {
  53759. return;
  53760. }
  53761. var mesh = node;
  53762. var boundingInfo = mesh.getBoundingInfo();
  53763. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53764. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53765. this._updateDirection();
  53766. }
  53767. };
  53768. Sound.prototype.clone = function () {
  53769. var _this = this;
  53770. if (!this._streaming) {
  53771. var setBufferAndRun = function () {
  53772. if (_this._isReadyToPlay) {
  53773. clonedSound._audioBuffer = _this.getAudioBuffer();
  53774. clonedSound._isReadyToPlay = true;
  53775. if (clonedSound.autoplay) {
  53776. clonedSound.play();
  53777. }
  53778. }
  53779. else {
  53780. window.setTimeout(setBufferAndRun, 300);
  53781. }
  53782. };
  53783. var currentOptions = {
  53784. autoplay: this.autoplay, loop: this.loop,
  53785. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53786. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53787. refDistance: this.refDistance, distanceModel: this.distanceModel
  53788. };
  53789. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53790. if (this.useCustomAttenuation) {
  53791. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53792. }
  53793. clonedSound.setPosition(this._position);
  53794. clonedSound.setPlaybackRate(this._playbackRate);
  53795. setBufferAndRun();
  53796. return clonedSound;
  53797. }
  53798. else {
  53799. return null;
  53800. }
  53801. };
  53802. Sound.prototype.getAudioBuffer = function () {
  53803. return this._audioBuffer;
  53804. };
  53805. Sound.prototype.serialize = function () {
  53806. var serializationObject = {
  53807. name: this.name,
  53808. url: this.name,
  53809. autoplay: this.autoplay,
  53810. loop: this.loop,
  53811. volume: this._volume,
  53812. spatialSound: this.spatialSound,
  53813. maxDistance: this.maxDistance,
  53814. rolloffFactor: this.rolloffFactor,
  53815. refDistance: this.refDistance,
  53816. distanceModel: this.distanceModel,
  53817. playbackRate: this._playbackRate,
  53818. panningModel: this._panningModel,
  53819. soundTrackId: this.soundTrackId
  53820. };
  53821. if (this.spatialSound) {
  53822. if (this._connectedMesh)
  53823. serializationObject.connectedMeshId = this._connectedMesh.id;
  53824. serializationObject.position = this._position.asArray();
  53825. serializationObject.refDistance = this.refDistance;
  53826. serializationObject.distanceModel = this.distanceModel;
  53827. serializationObject.isDirectional = this._isDirectional;
  53828. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  53829. serializationObject.coneInnerAngle = this._coneInnerAngle;
  53830. serializationObject.coneOuterAngle = this._coneOuterAngle;
  53831. serializationObject.coneOuterGain = this._coneOuterGain;
  53832. }
  53833. return serializationObject;
  53834. };
  53835. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  53836. var soundName = parsedSound.name;
  53837. var soundUrl;
  53838. if (parsedSound.url) {
  53839. soundUrl = rootUrl + parsedSound.url;
  53840. }
  53841. else {
  53842. soundUrl = rootUrl + soundName;
  53843. }
  53844. var options = {
  53845. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  53846. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  53847. rolloffFactor: parsedSound.rolloffFactor,
  53848. refDistance: parsedSound.refDistance,
  53849. distanceModel: parsedSound.distanceModel,
  53850. playbackRate: parsedSound.playbackRate
  53851. };
  53852. var newSound;
  53853. if (!sourceSound) {
  53854. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  53855. scene._addPendingData(newSound);
  53856. }
  53857. else {
  53858. var setBufferAndRun = function () {
  53859. if (sourceSound._isReadyToPlay) {
  53860. newSound._audioBuffer = sourceSound.getAudioBuffer();
  53861. newSound._isReadyToPlay = true;
  53862. if (newSound.autoplay) {
  53863. newSound.play();
  53864. }
  53865. }
  53866. else {
  53867. window.setTimeout(setBufferAndRun, 300);
  53868. }
  53869. };
  53870. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  53871. setBufferAndRun();
  53872. }
  53873. if (parsedSound.position) {
  53874. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  53875. newSound.setPosition(soundPosition);
  53876. }
  53877. if (parsedSound.isDirectional) {
  53878. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  53879. if (parsedSound.localDirectionToMesh) {
  53880. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  53881. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  53882. }
  53883. }
  53884. if (parsedSound.connectedMeshId) {
  53885. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  53886. if (connectedMesh) {
  53887. newSound.attachToMesh(connectedMesh);
  53888. }
  53889. }
  53890. return newSound;
  53891. };
  53892. return Sound;
  53893. }());
  53894. BABYLON.Sound = Sound;
  53895. })(BABYLON || (BABYLON = {}));
  53896. //# sourceMappingURL=babylon.sound.js.map
  53897. var BABYLON;
  53898. (function (BABYLON) {
  53899. var SoundTrack = /** @class */ (function () {
  53900. function SoundTrack(scene, options) {
  53901. this.id = -1;
  53902. this._isMainTrack = false;
  53903. this._isInitialized = false;
  53904. this._scene = scene;
  53905. this.soundCollection = new Array();
  53906. this._options = options;
  53907. if (!this._isMainTrack) {
  53908. this._scene.soundTracks.push(this);
  53909. this.id = this._scene.soundTracks.length - 1;
  53910. }
  53911. }
  53912. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  53913. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53914. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  53915. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  53916. if (this._options) {
  53917. if (this._options.volume) {
  53918. this._outputAudioNode.gain.value = this._options.volume;
  53919. }
  53920. if (this._options.mainTrack) {
  53921. this._isMainTrack = this._options.mainTrack;
  53922. }
  53923. }
  53924. this._isInitialized = true;
  53925. }
  53926. };
  53927. SoundTrack.prototype.dispose = function () {
  53928. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53929. if (this._connectedAnalyser) {
  53930. this._connectedAnalyser.stopDebugCanvas();
  53931. }
  53932. while (this.soundCollection.length) {
  53933. this.soundCollection[0].dispose();
  53934. }
  53935. if (this._outputAudioNode) {
  53936. this._outputAudioNode.disconnect();
  53937. }
  53938. this._outputAudioNode = null;
  53939. }
  53940. };
  53941. SoundTrack.prototype.AddSound = function (sound) {
  53942. if (!this._isInitialized) {
  53943. this._initializeSoundTrackAudioGraph();
  53944. }
  53945. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53946. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53947. }
  53948. if (sound.soundTrackId) {
  53949. if (sound.soundTrackId === -1) {
  53950. this._scene.mainSoundTrack.RemoveSound(sound);
  53951. }
  53952. else {
  53953. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53954. }
  53955. }
  53956. this.soundCollection.push(sound);
  53957. sound.soundTrackId = this.id;
  53958. };
  53959. SoundTrack.prototype.RemoveSound = function (sound) {
  53960. var index = this.soundCollection.indexOf(sound);
  53961. if (index !== -1) {
  53962. this.soundCollection.splice(index, 1);
  53963. }
  53964. };
  53965. SoundTrack.prototype.setVolume = function (newVolume) {
  53966. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53967. this._outputAudioNode.gain.value = newVolume;
  53968. }
  53969. };
  53970. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53971. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53972. for (var i = 0; i < this.soundCollection.length; i++) {
  53973. this.soundCollection[i].switchPanningModelToHRTF();
  53974. }
  53975. }
  53976. };
  53977. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53978. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53979. for (var i = 0; i < this.soundCollection.length; i++) {
  53980. this.soundCollection[i].switchPanningModelToEqualPower();
  53981. }
  53982. }
  53983. };
  53984. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53985. if (this._connectedAnalyser) {
  53986. this._connectedAnalyser.stopDebugCanvas();
  53987. }
  53988. this._connectedAnalyser = analyser;
  53989. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53990. this._outputAudioNode.disconnect();
  53991. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53992. }
  53993. };
  53994. return SoundTrack;
  53995. }());
  53996. BABYLON.SoundTrack = SoundTrack;
  53997. })(BABYLON || (BABYLON = {}));
  53998. //# sourceMappingURL=babylon.soundtrack.js.map
  53999. var BABYLON;
  54000. (function (BABYLON) {
  54001. var Analyser = /** @class */ (function () {
  54002. function Analyser(scene) {
  54003. this.SMOOTHING = 0.75;
  54004. this.FFT_SIZE = 512;
  54005. this.BARGRAPHAMPLITUDE = 256;
  54006. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54007. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54008. this._scene = scene;
  54009. this._audioEngine = BABYLON.Engine.audioEngine;
  54010. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  54011. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54012. this._webAudioAnalyser.minDecibels = -140;
  54013. this._webAudioAnalyser.maxDecibels = 0;
  54014. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54015. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54016. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54017. }
  54018. }
  54019. Analyser.prototype.getFrequencyBinCount = function () {
  54020. if (this._audioEngine.canUseWebAudio) {
  54021. return this._webAudioAnalyser.frequencyBinCount;
  54022. }
  54023. else {
  54024. return 0;
  54025. }
  54026. };
  54027. Analyser.prototype.getByteFrequencyData = function () {
  54028. if (this._audioEngine.canUseWebAudio) {
  54029. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54030. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54031. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54032. }
  54033. return this._byteFreqs;
  54034. };
  54035. Analyser.prototype.getByteTimeDomainData = function () {
  54036. if (this._audioEngine.canUseWebAudio) {
  54037. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54038. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54039. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54040. }
  54041. return this._byteTime;
  54042. };
  54043. Analyser.prototype.getFloatFrequencyData = function () {
  54044. if (this._audioEngine.canUseWebAudio) {
  54045. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54046. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54047. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54048. }
  54049. return this._floatFreqs;
  54050. };
  54051. Analyser.prototype.drawDebugCanvas = function () {
  54052. var _this = this;
  54053. if (this._audioEngine.canUseWebAudio) {
  54054. if (!this._debugCanvas) {
  54055. this._debugCanvas = document.createElement("canvas");
  54056. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54057. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54058. this._debugCanvas.style.position = "absolute";
  54059. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54060. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54061. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54062. document.body.appendChild(this._debugCanvas);
  54063. this._registerFunc = function () {
  54064. _this.drawDebugCanvas();
  54065. };
  54066. this._scene.registerBeforeRender(this._registerFunc);
  54067. }
  54068. if (this._registerFunc && this._debugCanvasContext) {
  54069. var workingArray = this.getByteFrequencyData();
  54070. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54071. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54072. // Draw the frequency domain chart.
  54073. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54074. var value = workingArray[i];
  54075. var percent = value / this.BARGRAPHAMPLITUDE;
  54076. var height = this.DEBUGCANVASSIZE.height * percent;
  54077. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54078. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54079. var hue = i / this.getFrequencyBinCount() * 360;
  54080. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54081. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54082. }
  54083. }
  54084. }
  54085. };
  54086. Analyser.prototype.stopDebugCanvas = function () {
  54087. if (this._debugCanvas) {
  54088. if (this._registerFunc) {
  54089. this._scene.unregisterBeforeRender(this._registerFunc);
  54090. this._registerFunc = null;
  54091. }
  54092. document.body.removeChild(this._debugCanvas);
  54093. this._debugCanvas = null;
  54094. this._debugCanvasContext = null;
  54095. }
  54096. };
  54097. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54098. if (this._audioEngine.canUseWebAudio) {
  54099. inputAudioNode.connect(this._webAudioAnalyser);
  54100. this._webAudioAnalyser.connect(outputAudioNode);
  54101. }
  54102. };
  54103. Analyser.prototype.dispose = function () {
  54104. if (this._audioEngine.canUseWebAudio) {
  54105. this._webAudioAnalyser.disconnect();
  54106. }
  54107. };
  54108. return Analyser;
  54109. }());
  54110. BABYLON.Analyser = Analyser;
  54111. })(BABYLON || (BABYLON = {}));
  54112. //# sourceMappingURL=babylon.analyser.js.map
  54113. var BABYLON;
  54114. (function (BABYLON) {
  54115. var CubeTexture = /** @class */ (function (_super) {
  54116. __extends(CubeTexture, _super);
  54117. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  54118. if (extensions === void 0) { extensions = null; }
  54119. if (noMipmap === void 0) { noMipmap = false; }
  54120. if (files === void 0) { files = null; }
  54121. if (onLoad === void 0) { onLoad = null; }
  54122. if (onError === void 0) { onError = null; }
  54123. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54124. if (prefiltered === void 0) { prefiltered = false; }
  54125. if (forcedExtension === void 0) { forcedExtension = null; }
  54126. var _this = _super.call(this, scene) || this;
  54127. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54128. _this.name = rootUrl;
  54129. _this.url = rootUrl;
  54130. _this._noMipmap = noMipmap;
  54131. _this.hasAlpha = false;
  54132. _this._format = format;
  54133. _this._prefiltered = prefiltered;
  54134. _this.isCube = true;
  54135. _this._textureMatrix = BABYLON.Matrix.Identity();
  54136. if (prefiltered) {
  54137. _this.gammaSpace = false;
  54138. }
  54139. if (!rootUrl && !files) {
  54140. return _this;
  54141. }
  54142. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  54143. var lastDot = rootUrl.lastIndexOf(".");
  54144. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  54145. var isDDS = (extension === ".dds");
  54146. if (!files) {
  54147. if (!isDDS && !extensions) {
  54148. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  54149. }
  54150. files = [];
  54151. if (extensions) {
  54152. for (var index = 0; index < extensions.length; index++) {
  54153. files.push(rootUrl + extensions[index]);
  54154. }
  54155. }
  54156. }
  54157. _this._files = files;
  54158. if (!_this._texture) {
  54159. if (!scene.useDelayedTextureLoading) {
  54160. if (prefiltered) {
  54161. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  54162. }
  54163. else {
  54164. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  54165. }
  54166. }
  54167. else {
  54168. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54169. }
  54170. }
  54171. else if (onLoad) {
  54172. if (_this._texture.isReady) {
  54173. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  54174. }
  54175. else {
  54176. _this._texture.onLoadedObservable.add(onLoad);
  54177. }
  54178. }
  54179. return _this;
  54180. }
  54181. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  54182. return new CubeTexture("", scene, null, noMipmap, files);
  54183. };
  54184. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  54185. if (forcedExtension === void 0) { forcedExtension = null; }
  54186. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  54187. };
  54188. // Methods
  54189. CubeTexture.prototype.delayLoad = function () {
  54190. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54191. return;
  54192. }
  54193. var scene = this.getScene();
  54194. if (!scene) {
  54195. return;
  54196. }
  54197. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54198. this._texture = this._getFromCache(this.url, this._noMipmap);
  54199. if (!this._texture) {
  54200. if (this._prefiltered) {
  54201. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  54202. }
  54203. else {
  54204. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  54205. }
  54206. }
  54207. };
  54208. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  54209. return this._textureMatrix;
  54210. };
  54211. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  54212. this._textureMatrix = value;
  54213. };
  54214. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54215. var texture = BABYLON.SerializationHelper.Parse(function () {
  54216. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  54217. }, parsedTexture, scene);
  54218. // Animations
  54219. if (parsedTexture.animations) {
  54220. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  54221. var parsedAnimation = parsedTexture.animations[animationIndex];
  54222. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54223. }
  54224. }
  54225. return texture;
  54226. };
  54227. CubeTexture.prototype.clone = function () {
  54228. var _this = this;
  54229. return BABYLON.SerializationHelper.Clone(function () {
  54230. var scene = _this.getScene();
  54231. if (!scene) {
  54232. return _this;
  54233. }
  54234. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  54235. }, this);
  54236. };
  54237. return CubeTexture;
  54238. }(BABYLON.BaseTexture));
  54239. BABYLON.CubeTexture = CubeTexture;
  54240. })(BABYLON || (BABYLON = {}));
  54241. //# sourceMappingURL=babylon.cubeTexture.js.map
  54242. var BABYLON;
  54243. (function (BABYLON) {
  54244. var RenderTargetTexture = /** @class */ (function (_super) {
  54245. __extends(RenderTargetTexture, _super);
  54246. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  54247. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  54248. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54249. if (isCube === void 0) { isCube = false; }
  54250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54251. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54252. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  54253. if (isMulti === void 0) { isMulti = false; }
  54254. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54255. _this.isCube = isCube;
  54256. /**
  54257. * Use this list to define the list of mesh you want to render.
  54258. */
  54259. _this.renderList = new Array();
  54260. _this.renderParticles = true;
  54261. _this.renderSprites = false;
  54262. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  54263. _this.ignoreCameraViewport = false;
  54264. // Events
  54265. /**
  54266. * An event triggered when the texture is unbind.
  54267. * @type {BABYLON.Observable}
  54268. */
  54269. _this.onBeforeBindObservable = new BABYLON.Observable();
  54270. /**
  54271. * An event triggered when the texture is unbind.
  54272. * @type {BABYLON.Observable}
  54273. */
  54274. _this.onAfterUnbindObservable = new BABYLON.Observable();
  54275. /**
  54276. * An event triggered before rendering the texture
  54277. * @type {BABYLON.Observable}
  54278. */
  54279. _this.onBeforeRenderObservable = new BABYLON.Observable();
  54280. /**
  54281. * An event triggered after rendering the texture
  54282. * @type {BABYLON.Observable}
  54283. */
  54284. _this.onAfterRenderObservable = new BABYLON.Observable();
  54285. /**
  54286. * An event triggered after the texture clear
  54287. * @type {BABYLON.Observable}
  54288. */
  54289. _this.onClearObservable = new BABYLON.Observable();
  54290. _this._currentRefreshId = -1;
  54291. _this._refreshRate = 1;
  54292. _this._samples = 1;
  54293. scene = _this.getScene();
  54294. if (!scene) {
  54295. return _this;
  54296. }
  54297. _this._engine = scene.getEngine();
  54298. _this.name = name;
  54299. _this.isRenderTarget = true;
  54300. _this._initialSizeParameter = size;
  54301. _this._processSizeParameter(size);
  54302. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  54303. });
  54304. _this._generateMipMaps = generateMipMaps ? true : false;
  54305. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  54306. // Rendering groups
  54307. _this._renderingManager = new BABYLON.RenderingManager(scene);
  54308. if (isMulti) {
  54309. return _this;
  54310. }
  54311. _this._renderTargetOptions = {
  54312. generateMipMaps: generateMipMaps,
  54313. type: type,
  54314. samplingMode: samplingMode,
  54315. generateDepthBuffer: generateDepthBuffer,
  54316. generateStencilBuffer: generateStencilBuffer
  54317. };
  54318. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  54319. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54320. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54321. }
  54322. if (isCube) {
  54323. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  54324. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  54325. _this._textureMatrix = BABYLON.Matrix.Identity();
  54326. }
  54327. else {
  54328. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  54329. }
  54330. return _this;
  54331. }
  54332. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  54333. get: function () {
  54334. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  54335. },
  54336. enumerable: true,
  54337. configurable: true
  54338. });
  54339. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54340. get: function () {
  54341. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54342. },
  54343. enumerable: true,
  54344. configurable: true
  54345. });
  54346. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54347. get: function () {
  54348. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54349. },
  54350. enumerable: true,
  54351. configurable: true
  54352. });
  54353. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54354. set: function (callback) {
  54355. if (this._onAfterUnbindObserver) {
  54356. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54357. }
  54358. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54359. },
  54360. enumerable: true,
  54361. configurable: true
  54362. });
  54363. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54364. set: function (callback) {
  54365. if (this._onBeforeRenderObserver) {
  54366. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54367. }
  54368. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54369. },
  54370. enumerable: true,
  54371. configurable: true
  54372. });
  54373. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54374. set: function (callback) {
  54375. if (this._onAfterRenderObserver) {
  54376. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54377. }
  54378. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54379. },
  54380. enumerable: true,
  54381. configurable: true
  54382. });
  54383. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54384. set: function (callback) {
  54385. if (this._onClearObserver) {
  54386. this.onClearObservable.remove(this._onClearObserver);
  54387. }
  54388. this._onClearObserver = this.onClearObservable.add(callback);
  54389. },
  54390. enumerable: true,
  54391. configurable: true
  54392. });
  54393. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54394. get: function () {
  54395. return this._renderTargetOptions;
  54396. },
  54397. enumerable: true,
  54398. configurable: true
  54399. });
  54400. RenderTargetTexture.prototype._onRatioRescale = function () {
  54401. if (this._sizeRatio) {
  54402. this.resize(this._initialSizeParameter);
  54403. }
  54404. };
  54405. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54406. if (size.ratio) {
  54407. this._sizeRatio = size.ratio;
  54408. this._size = {
  54409. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54410. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54411. };
  54412. }
  54413. else {
  54414. this._size = size;
  54415. }
  54416. };
  54417. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54418. get: function () {
  54419. return this._samples;
  54420. },
  54421. set: function (value) {
  54422. if (this._samples === value) {
  54423. return;
  54424. }
  54425. var scene = this.getScene();
  54426. if (!scene) {
  54427. return;
  54428. }
  54429. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54430. },
  54431. enumerable: true,
  54432. configurable: true
  54433. });
  54434. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54435. this._currentRefreshId = -1;
  54436. };
  54437. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54438. get: function () {
  54439. return this._refreshRate;
  54440. },
  54441. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54442. set: function (value) {
  54443. this._refreshRate = value;
  54444. this.resetRefreshCounter();
  54445. },
  54446. enumerable: true,
  54447. configurable: true
  54448. });
  54449. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54450. if (!this._postProcessManager) {
  54451. var scene = this.getScene();
  54452. if (!scene) {
  54453. return;
  54454. }
  54455. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54456. this._postProcesses = new Array();
  54457. }
  54458. this._postProcesses.push(postProcess);
  54459. this._postProcesses[0].autoClear = false;
  54460. };
  54461. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54462. if (!this._postProcesses) {
  54463. return;
  54464. }
  54465. if (dispose) {
  54466. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54467. var postProcess = _a[_i];
  54468. postProcess.dispose();
  54469. }
  54470. }
  54471. this._postProcesses = [];
  54472. };
  54473. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54474. if (!this._postProcesses) {
  54475. return;
  54476. }
  54477. var index = this._postProcesses.indexOf(postProcess);
  54478. if (index === -1) {
  54479. return;
  54480. }
  54481. this._postProcesses.splice(index, 1);
  54482. if (this._postProcesses.length > 0) {
  54483. this._postProcesses[0].autoClear = false;
  54484. }
  54485. };
  54486. RenderTargetTexture.prototype._shouldRender = function () {
  54487. if (this._currentRefreshId === -1) {
  54488. this._currentRefreshId = 1;
  54489. return true;
  54490. }
  54491. if (this.refreshRate === this._currentRefreshId) {
  54492. this._currentRefreshId = 1;
  54493. return true;
  54494. }
  54495. this._currentRefreshId++;
  54496. return false;
  54497. };
  54498. RenderTargetTexture.prototype.getRenderSize = function () {
  54499. if (this._size.width) {
  54500. return this._size.width;
  54501. }
  54502. return this._size;
  54503. };
  54504. RenderTargetTexture.prototype.getRenderWidth = function () {
  54505. if (this._size.width) {
  54506. return this._size.width;
  54507. }
  54508. return this._size;
  54509. };
  54510. RenderTargetTexture.prototype.getRenderHeight = function () {
  54511. if (this._size.width) {
  54512. return this._size.height;
  54513. }
  54514. return this._size;
  54515. };
  54516. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54517. get: function () {
  54518. return true;
  54519. },
  54520. enumerable: true,
  54521. configurable: true
  54522. });
  54523. RenderTargetTexture.prototype.scale = function (ratio) {
  54524. var newSize = this.getRenderSize() * ratio;
  54525. this.resize(newSize);
  54526. };
  54527. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54528. if (this.isCube) {
  54529. return this._textureMatrix;
  54530. }
  54531. return _super.prototype.getReflectionTextureMatrix.call(this);
  54532. };
  54533. RenderTargetTexture.prototype.resize = function (size) {
  54534. this.releaseInternalTexture();
  54535. var scene = this.getScene();
  54536. if (!scene) {
  54537. return;
  54538. }
  54539. this._processSizeParameter(size);
  54540. if (this.isCube) {
  54541. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54542. }
  54543. else {
  54544. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54545. }
  54546. };
  54547. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54548. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54549. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54550. var scene = this.getScene();
  54551. if (!scene) {
  54552. return;
  54553. }
  54554. var engine = scene.getEngine();
  54555. if (this.useCameraPostProcesses !== undefined) {
  54556. useCameraPostProcess = this.useCameraPostProcesses;
  54557. }
  54558. if (this._waitingRenderList) {
  54559. this.renderList = [];
  54560. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54561. var id = this._waitingRenderList[index];
  54562. var mesh_1 = scene.getMeshByID(id);
  54563. if (mesh_1) {
  54564. this.renderList.push(mesh_1);
  54565. }
  54566. }
  54567. delete this._waitingRenderList;
  54568. }
  54569. // Is predicate defined?
  54570. if (this.renderListPredicate) {
  54571. if (this.renderList) {
  54572. this.renderList.splice(0); // Clear previous renderList
  54573. }
  54574. else {
  54575. this.renderList = [];
  54576. }
  54577. var scene = this.getScene();
  54578. if (!scene) {
  54579. return;
  54580. }
  54581. var sceneMeshes = scene.meshes;
  54582. for (var index = 0; index < sceneMeshes.length; index++) {
  54583. var mesh = sceneMeshes[index];
  54584. if (this.renderListPredicate(mesh)) {
  54585. this.renderList.push(mesh);
  54586. }
  54587. }
  54588. }
  54589. this.onBeforeBindObservable.notifyObservers(this);
  54590. // Set custom projection.
  54591. // Needs to be before binding to prevent changing the aspect ratio.
  54592. var camera;
  54593. if (this.activeCamera) {
  54594. camera = this.activeCamera;
  54595. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54596. if (this.activeCamera !== scene.activeCamera) {
  54597. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54598. }
  54599. }
  54600. else {
  54601. camera = scene.activeCamera;
  54602. if (camera) {
  54603. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54604. }
  54605. }
  54606. // Prepare renderingManager
  54607. this._renderingManager.reset();
  54608. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54609. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54610. var sceneRenderId = scene.getRenderId();
  54611. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54612. var mesh = currentRenderList[meshIndex];
  54613. if (mesh) {
  54614. if (!mesh.isReady()) {
  54615. // Reset _currentRefreshId
  54616. this.resetRefreshCounter();
  54617. continue;
  54618. }
  54619. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54620. var isMasked = void 0;
  54621. if (!this.renderList && camera) {
  54622. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54623. }
  54624. else {
  54625. isMasked = false;
  54626. }
  54627. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54628. mesh._activate(sceneRenderId);
  54629. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54630. var subMesh = mesh.subMeshes[subIndex];
  54631. scene._activeIndices.addCount(subMesh.indexCount, false);
  54632. this._renderingManager.dispatch(subMesh, mesh);
  54633. }
  54634. }
  54635. }
  54636. }
  54637. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54638. var particleSystem = scene.particleSystems[particleIndex];
  54639. var emitter = particleSystem.emitter;
  54640. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54641. continue;
  54642. }
  54643. if (currentRenderList.indexOf(emitter) >= 0) {
  54644. this._renderingManager.dispatchParticles(particleSystem);
  54645. }
  54646. }
  54647. if (this.isCube) {
  54648. for (var face = 0; face < 6; face++) {
  54649. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54650. scene.incrementRenderId();
  54651. scene.resetCachedMaterial();
  54652. }
  54653. }
  54654. else {
  54655. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54656. }
  54657. this.onAfterUnbindObservable.notifyObservers(this);
  54658. if (scene.activeCamera) {
  54659. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54660. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54661. }
  54662. engine.setViewport(scene.activeCamera.viewport);
  54663. }
  54664. scene.resetCachedMaterial();
  54665. };
  54666. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54667. var minimum = 128;
  54668. var x = renderDimension * scale;
  54669. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54670. // Ensure we don't exceed the render dimension (while staying POT)
  54671. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54672. };
  54673. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54674. var _this = this;
  54675. if (!this._texture) {
  54676. return;
  54677. }
  54678. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54679. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54680. });
  54681. };
  54682. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54683. var scene = this.getScene();
  54684. if (!scene) {
  54685. return;
  54686. }
  54687. var engine = scene.getEngine();
  54688. if (!this._texture) {
  54689. return;
  54690. }
  54691. // Bind
  54692. if (this._postProcessManager) {
  54693. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54694. }
  54695. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54696. if (this._texture) {
  54697. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54698. }
  54699. }
  54700. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54701. // Clear
  54702. if (this.onClearObservable.hasObservers()) {
  54703. this.onClearObservable.notifyObservers(engine);
  54704. }
  54705. else {
  54706. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54707. }
  54708. if (!this._doNotChangeAspectRatio) {
  54709. scene.updateTransformMatrix(true);
  54710. }
  54711. // Render
  54712. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54713. if (this._postProcessManager) {
  54714. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54715. }
  54716. else if (useCameraPostProcess) {
  54717. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54718. }
  54719. if (!this._doNotChangeAspectRatio) {
  54720. scene.updateTransformMatrix(true);
  54721. }
  54722. // Dump ?
  54723. if (dumpForDebug) {
  54724. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54725. }
  54726. // Unbind
  54727. if (!this.isCube || faceIndex === 5) {
  54728. if (this.isCube) {
  54729. if (faceIndex === 5) {
  54730. engine.generateMipMapsForCubemap(this._texture);
  54731. }
  54732. }
  54733. this.unbindFrameBuffer(engine, faceIndex);
  54734. }
  54735. else {
  54736. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54737. }
  54738. };
  54739. /**
  54740. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54741. * This allowed control for front to back rendering or reversly depending of the special needs.
  54742. *
  54743. * @param renderingGroupId The rendering group id corresponding to its index
  54744. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54745. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54746. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54747. */
  54748. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54749. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54750. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54751. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54752. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54753. };
  54754. /**
  54755. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54756. *
  54757. * @param renderingGroupId The rendering group id corresponding to its index
  54758. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54759. */
  54760. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54761. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54762. };
  54763. RenderTargetTexture.prototype.clone = function () {
  54764. var textureSize = this.getSize();
  54765. 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);
  54766. // Base texture
  54767. newTexture.hasAlpha = this.hasAlpha;
  54768. newTexture.level = this.level;
  54769. // RenderTarget Texture
  54770. newTexture.coordinatesMode = this.coordinatesMode;
  54771. if (this.renderList) {
  54772. newTexture.renderList = this.renderList.slice(0);
  54773. }
  54774. return newTexture;
  54775. };
  54776. RenderTargetTexture.prototype.serialize = function () {
  54777. if (!this.name) {
  54778. return null;
  54779. }
  54780. var serializationObject = _super.prototype.serialize.call(this);
  54781. serializationObject.renderTargetSize = this.getRenderSize();
  54782. serializationObject.renderList = [];
  54783. if (this.renderList) {
  54784. for (var index = 0; index < this.renderList.length; index++) {
  54785. serializationObject.renderList.push(this.renderList[index].id);
  54786. }
  54787. }
  54788. return serializationObject;
  54789. };
  54790. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54791. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54792. var objBuffer = this.getInternalTexture();
  54793. var scene = this.getScene();
  54794. if (objBuffer && scene) {
  54795. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54796. }
  54797. };
  54798. RenderTargetTexture.prototype.dispose = function () {
  54799. if (this._postProcessManager) {
  54800. this._postProcessManager.dispose();
  54801. this._postProcessManager = null;
  54802. }
  54803. this.clearPostProcesses(true);
  54804. if (this._resizeObserver) {
  54805. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54806. this._resizeObserver = null;
  54807. }
  54808. this.renderList = null;
  54809. // Remove from custom render targets
  54810. var scene = this.getScene();
  54811. if (!scene) {
  54812. return;
  54813. }
  54814. var index = scene.customRenderTargets.indexOf(this);
  54815. if (index >= 0) {
  54816. scene.customRenderTargets.splice(index, 1);
  54817. }
  54818. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  54819. var camera = _a[_i];
  54820. index = camera.customRenderTargets.indexOf(this);
  54821. if (index >= 0) {
  54822. camera.customRenderTargets.splice(index, 1);
  54823. }
  54824. }
  54825. _super.prototype.dispose.call(this);
  54826. };
  54827. RenderTargetTexture.prototype._rebuild = function () {
  54828. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54829. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54830. }
  54831. if (this._postProcessManager) {
  54832. this._postProcessManager._rebuild();
  54833. }
  54834. };
  54835. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  54836. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  54837. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  54838. return RenderTargetTexture;
  54839. }(BABYLON.Texture));
  54840. BABYLON.RenderTargetTexture = RenderTargetTexture;
  54841. })(BABYLON || (BABYLON = {}));
  54842. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  54843. var BABYLON;
  54844. (function (BABYLON) {
  54845. ;
  54846. var MultiRenderTarget = /** @class */ (function (_super) {
  54847. __extends(MultiRenderTarget, _super);
  54848. function MultiRenderTarget(name, size, count, scene, options) {
  54849. var _this = this;
  54850. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  54851. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  54852. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  54853. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  54854. _this._engine = scene.getEngine();
  54855. if (!_this.isSupported) {
  54856. _this.dispose();
  54857. return;
  54858. }
  54859. var types = [];
  54860. var samplingModes = [];
  54861. for (var i = 0; i < count; i++) {
  54862. if (options && options.types && options.types[i] !== undefined) {
  54863. types.push(options.types[i]);
  54864. }
  54865. else {
  54866. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54867. }
  54868. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  54869. samplingModes.push(options.samplingModes[i]);
  54870. }
  54871. else {
  54872. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54873. }
  54874. }
  54875. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  54876. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  54877. _this._size = size;
  54878. _this._multiRenderTargetOptions = {
  54879. samplingModes: samplingModes,
  54880. generateMipMaps: generateMipMaps,
  54881. generateDepthBuffer: generateDepthBuffer,
  54882. generateStencilBuffer: generateStencilBuffer,
  54883. generateDepthTexture: generateDepthTexture,
  54884. types: types,
  54885. textureCount: count
  54886. };
  54887. _this._createInternalTextures();
  54888. _this._createTextures();
  54889. return _this;
  54890. }
  54891. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  54892. get: function () {
  54893. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  54894. },
  54895. enumerable: true,
  54896. configurable: true
  54897. });
  54898. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  54899. get: function () {
  54900. return this._textures;
  54901. },
  54902. enumerable: true,
  54903. configurable: true
  54904. });
  54905. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  54906. get: function () {
  54907. return this._textures[this._textures.length - 1];
  54908. },
  54909. enumerable: true,
  54910. configurable: true
  54911. });
  54912. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  54913. set: function (wrap) {
  54914. if (this._textures) {
  54915. for (var i = 0; i < this._textures.length; i++) {
  54916. this._textures[i].wrapU = wrap;
  54917. }
  54918. }
  54919. },
  54920. enumerable: true,
  54921. configurable: true
  54922. });
  54923. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  54924. set: function (wrap) {
  54925. if (this._textures) {
  54926. for (var i = 0; i < this._textures.length; i++) {
  54927. this._textures[i].wrapV = wrap;
  54928. }
  54929. }
  54930. },
  54931. enumerable: true,
  54932. configurable: true
  54933. });
  54934. MultiRenderTarget.prototype._rebuild = function () {
  54935. this.releaseInternalTextures();
  54936. this._createInternalTextures();
  54937. for (var i = 0; i < this._internalTextures.length; i++) {
  54938. var texture = this._textures[i];
  54939. texture._texture = this._internalTextures[i];
  54940. }
  54941. // Keeps references to frame buffer and stencil/depth buffer
  54942. this._texture = this._internalTextures[0];
  54943. };
  54944. MultiRenderTarget.prototype._createInternalTextures = function () {
  54945. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54946. };
  54947. MultiRenderTarget.prototype._createTextures = function () {
  54948. this._textures = [];
  54949. for (var i = 0; i < this._internalTextures.length; i++) {
  54950. var texture = new BABYLON.Texture(null, this.getScene());
  54951. texture._texture = this._internalTextures[i];
  54952. this._textures.push(texture);
  54953. }
  54954. // Keeps references to frame buffer and stencil/depth buffer
  54955. this._texture = this._internalTextures[0];
  54956. };
  54957. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54958. get: function () {
  54959. return this._samples;
  54960. },
  54961. set: function (value) {
  54962. if (this._samples === value) {
  54963. return;
  54964. }
  54965. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54966. },
  54967. enumerable: true,
  54968. configurable: true
  54969. });
  54970. MultiRenderTarget.prototype.resize = function (size) {
  54971. this.releaseInternalTextures();
  54972. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54973. this._createInternalTextures();
  54974. };
  54975. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54976. var _this = this;
  54977. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54978. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54979. });
  54980. };
  54981. MultiRenderTarget.prototype.dispose = function () {
  54982. this.releaseInternalTextures();
  54983. _super.prototype.dispose.call(this);
  54984. };
  54985. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54986. if (!this._internalTextures) {
  54987. return;
  54988. }
  54989. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54990. if (this._internalTextures[i] !== undefined) {
  54991. this._internalTextures[i].dispose();
  54992. this._internalTextures.splice(i, 1);
  54993. }
  54994. }
  54995. };
  54996. return MultiRenderTarget;
  54997. }(BABYLON.RenderTargetTexture));
  54998. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54999. })(BABYLON || (BABYLON = {}));
  55000. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  55001. var BABYLON;
  55002. (function (BABYLON) {
  55003. var MirrorTexture = /** @class */ (function (_super) {
  55004. __extends(MirrorTexture, _super);
  55005. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  55006. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55008. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55009. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  55010. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  55011. _this._transformMatrix = BABYLON.Matrix.Zero();
  55012. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  55013. _this._adaptiveBlurKernel = 0;
  55014. _this._blurKernelX = 0;
  55015. _this._blurKernelY = 0;
  55016. _this._blurRatio = 1.0;
  55017. _this.ignoreCameraViewport = true;
  55018. _this.onBeforeRenderObservable.add(function () {
  55019. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  55020. _this._savedViewMatrix = scene.getViewMatrix();
  55021. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  55022. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  55023. scene.clipPlane = _this.mirrorPlane;
  55024. scene.getEngine().cullBackFaces = false;
  55025. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  55026. });
  55027. _this.onAfterRenderObservable.add(function () {
  55028. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  55029. scene.getEngine().cullBackFaces = true;
  55030. scene._mirroredCameraPosition = null;
  55031. delete scene.clipPlane;
  55032. });
  55033. return _this;
  55034. }
  55035. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  55036. get: function () {
  55037. return this._blurRatio;
  55038. },
  55039. set: function (value) {
  55040. if (this._blurRatio === value) {
  55041. return;
  55042. }
  55043. this._blurRatio = value;
  55044. this._preparePostProcesses();
  55045. },
  55046. enumerable: true,
  55047. configurable: true
  55048. });
  55049. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  55050. set: function (value) {
  55051. this._adaptiveBlurKernel = value;
  55052. this._autoComputeBlurKernel();
  55053. },
  55054. enumerable: true,
  55055. configurable: true
  55056. });
  55057. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  55058. set: function (value) {
  55059. this.blurKernelX = value;
  55060. this.blurKernelY = value;
  55061. },
  55062. enumerable: true,
  55063. configurable: true
  55064. });
  55065. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  55066. get: function () {
  55067. return this._blurKernelX;
  55068. },
  55069. set: function (value) {
  55070. if (this._blurKernelX === value) {
  55071. return;
  55072. }
  55073. this._blurKernelX = value;
  55074. this._preparePostProcesses();
  55075. },
  55076. enumerable: true,
  55077. configurable: true
  55078. });
  55079. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  55080. get: function () {
  55081. return this._blurKernelY;
  55082. },
  55083. set: function (value) {
  55084. if (this._blurKernelY === value) {
  55085. return;
  55086. }
  55087. this._blurKernelY = value;
  55088. this._preparePostProcesses();
  55089. },
  55090. enumerable: true,
  55091. configurable: true
  55092. });
  55093. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  55094. var engine = this.getScene().getEngine();
  55095. var dw = this.getRenderWidth() / engine.getRenderWidth();
  55096. var dh = this.getRenderHeight() / engine.getRenderHeight();
  55097. this.blurKernelX = this._adaptiveBlurKernel * dw;
  55098. this.blurKernelY = this._adaptiveBlurKernel * dh;
  55099. };
  55100. MirrorTexture.prototype._onRatioRescale = function () {
  55101. if (this._sizeRatio) {
  55102. this.resize(this._initialSizeParameter);
  55103. if (!this._adaptiveBlurKernel) {
  55104. this._preparePostProcesses();
  55105. }
  55106. }
  55107. if (this._adaptiveBlurKernel) {
  55108. this._autoComputeBlurKernel();
  55109. }
  55110. };
  55111. MirrorTexture.prototype._preparePostProcesses = function () {
  55112. this.clearPostProcesses(true);
  55113. if (this._blurKernelX && this._blurKernelY) {
  55114. var engine = this.getScene().getEngine();
  55115. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55116. 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);
  55117. this._blurX.autoClear = false;
  55118. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  55119. this._blurX.outputTexture = this._texture;
  55120. }
  55121. else {
  55122. this._blurX.alwaysForcePOT = true;
  55123. }
  55124. 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);
  55125. this._blurY.autoClear = false;
  55126. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  55127. this.addPostProcess(this._blurX);
  55128. this.addPostProcess(this._blurY);
  55129. }
  55130. else {
  55131. if (this._blurY) {
  55132. this.removePostProcess(this._blurY);
  55133. this._blurY.dispose();
  55134. this._blurY = null;
  55135. }
  55136. if (this._blurX) {
  55137. this.removePostProcess(this._blurX);
  55138. this._blurX.dispose();
  55139. this._blurX = null;
  55140. }
  55141. }
  55142. };
  55143. MirrorTexture.prototype.clone = function () {
  55144. var scene = this.getScene();
  55145. if (!scene) {
  55146. return this;
  55147. }
  55148. var textureSize = this.getSize();
  55149. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  55150. // Base texture
  55151. newTexture.hasAlpha = this.hasAlpha;
  55152. newTexture.level = this.level;
  55153. // Mirror Texture
  55154. newTexture.mirrorPlane = this.mirrorPlane.clone();
  55155. if (this.renderList) {
  55156. newTexture.renderList = this.renderList.slice(0);
  55157. }
  55158. return newTexture;
  55159. };
  55160. MirrorTexture.prototype.serialize = function () {
  55161. if (!this.name) {
  55162. return null;
  55163. }
  55164. var serializationObject = _super.prototype.serialize.call(this);
  55165. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  55166. return serializationObject;
  55167. };
  55168. return MirrorTexture;
  55169. }(BABYLON.RenderTargetTexture));
  55170. BABYLON.MirrorTexture = MirrorTexture;
  55171. })(BABYLON || (BABYLON = {}));
  55172. //# sourceMappingURL=babylon.mirrorTexture.js.map
  55173. var BABYLON;
  55174. (function (BABYLON) {
  55175. /**
  55176. * Creates a refraction texture used by refraction channel of the standard material.
  55177. * @param name the texture name
  55178. * @param size size of the underlying texture
  55179. * @param scene root scene
  55180. */
  55181. var RefractionTexture = /** @class */ (function (_super) {
  55182. __extends(RefractionTexture, _super);
  55183. function RefractionTexture(name, size, scene, generateMipMaps) {
  55184. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  55185. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  55186. _this.depth = 2.0;
  55187. _this.onBeforeRenderObservable.add(function () {
  55188. scene.clipPlane = _this.refractionPlane;
  55189. });
  55190. _this.onAfterRenderObservable.add(function () {
  55191. delete scene.clipPlane;
  55192. });
  55193. return _this;
  55194. }
  55195. RefractionTexture.prototype.clone = function () {
  55196. var scene = this.getScene();
  55197. if (!scene) {
  55198. return this;
  55199. }
  55200. var textureSize = this.getSize();
  55201. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  55202. // Base texture
  55203. newTexture.hasAlpha = this.hasAlpha;
  55204. newTexture.level = this.level;
  55205. // Refraction Texture
  55206. newTexture.refractionPlane = this.refractionPlane.clone();
  55207. if (this.renderList) {
  55208. newTexture.renderList = this.renderList.slice(0);
  55209. }
  55210. newTexture.depth = this.depth;
  55211. return newTexture;
  55212. };
  55213. RefractionTexture.prototype.serialize = function () {
  55214. if (!this.name) {
  55215. return null;
  55216. }
  55217. var serializationObject = _super.prototype.serialize.call(this);
  55218. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  55219. serializationObject.depth = this.depth;
  55220. return serializationObject;
  55221. };
  55222. return RefractionTexture;
  55223. }(BABYLON.RenderTargetTexture));
  55224. BABYLON.RefractionTexture = RefractionTexture;
  55225. })(BABYLON || (BABYLON = {}));
  55226. //# sourceMappingURL=babylon.refractionTexture.js.map
  55227. var BABYLON;
  55228. (function (BABYLON) {
  55229. var DynamicTexture = /** @class */ (function (_super) {
  55230. __extends(DynamicTexture, _super);
  55231. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  55232. if (scene === void 0) { scene = null; }
  55233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55234. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55235. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  55236. _this.name = name;
  55237. _this._engine = _this.getScene().getEngine();
  55238. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55239. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55240. _this._generateMipMaps = generateMipMaps;
  55241. if (options.getContext) {
  55242. _this._canvas = options;
  55243. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55244. }
  55245. else {
  55246. _this._canvas = document.createElement("canvas");
  55247. if (options.width) {
  55248. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55249. }
  55250. else {
  55251. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  55252. }
  55253. }
  55254. var textureSize = _this.getSize();
  55255. _this._canvas.width = textureSize.width;
  55256. _this._canvas.height = textureSize.height;
  55257. _this._context = _this._canvas.getContext("2d");
  55258. return _this;
  55259. }
  55260. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  55261. get: function () {
  55262. return true;
  55263. },
  55264. enumerable: true,
  55265. configurable: true
  55266. });
  55267. DynamicTexture.prototype._recreate = function (textureSize) {
  55268. this._canvas.width = textureSize.width;
  55269. this._canvas.height = textureSize.height;
  55270. this.releaseInternalTexture();
  55271. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  55272. };
  55273. DynamicTexture.prototype.scale = function (ratio) {
  55274. var textureSize = this.getSize();
  55275. textureSize.width *= ratio;
  55276. textureSize.height *= ratio;
  55277. this._recreate(textureSize);
  55278. };
  55279. DynamicTexture.prototype.scaleTo = function (width, height) {
  55280. var textureSize = this.getSize();
  55281. textureSize.width = width;
  55282. textureSize.height = height;
  55283. this._recreate(textureSize);
  55284. };
  55285. DynamicTexture.prototype.getContext = function () {
  55286. return this._context;
  55287. };
  55288. DynamicTexture.prototype.clear = function () {
  55289. var size = this.getSize();
  55290. this._context.fillRect(0, 0, size.width, size.height);
  55291. };
  55292. DynamicTexture.prototype.update = function (invertY) {
  55293. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  55294. };
  55295. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  55296. if (update === void 0) { update = true; }
  55297. var size = this.getSize();
  55298. if (clearColor) {
  55299. this._context.fillStyle = clearColor;
  55300. this._context.fillRect(0, 0, size.width, size.height);
  55301. }
  55302. this._context.font = font;
  55303. if (x === null || x === undefined) {
  55304. var textSize = this._context.measureText(text);
  55305. x = (size.width - textSize.width) / 2;
  55306. }
  55307. if (y === null || y === undefined) {
  55308. var fontSize = parseInt((font.replace(/\D/g, '')));
  55309. ;
  55310. y = (size.height / 2) + (fontSize / 3.65);
  55311. }
  55312. this._context.fillStyle = color;
  55313. this._context.fillText(text, x, y);
  55314. if (update) {
  55315. this.update(invertY);
  55316. }
  55317. };
  55318. DynamicTexture.prototype.clone = function () {
  55319. var scene = this.getScene();
  55320. if (!scene) {
  55321. return this;
  55322. }
  55323. var textureSize = this.getSize();
  55324. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  55325. // Base texture
  55326. newTexture.hasAlpha = this.hasAlpha;
  55327. newTexture.level = this.level;
  55328. // Dynamic Texture
  55329. newTexture.wrapU = this.wrapU;
  55330. newTexture.wrapV = this.wrapV;
  55331. return newTexture;
  55332. };
  55333. DynamicTexture.prototype._rebuild = function () {
  55334. this.update();
  55335. };
  55336. return DynamicTexture;
  55337. }(BABYLON.Texture));
  55338. BABYLON.DynamicTexture = DynamicTexture;
  55339. })(BABYLON || (BABYLON = {}));
  55340. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55341. var BABYLON;
  55342. (function (BABYLON) {
  55343. var VideoTexture = /** @class */ (function (_super) {
  55344. __extends(VideoTexture, _super);
  55345. /**
  55346. * Creates a video texture.
  55347. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55348. * @param {string | null} name optional name, will detect from video source, if not defined
  55349. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55350. * @param {BABYLON.Scene} scene is obviously the current scene.
  55351. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55352. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55353. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55354. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55355. */
  55356. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55357. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55358. if (invertY === void 0) { invertY = false; }
  55359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55360. if (settings === void 0) { settings = {
  55361. autoPlay: true,
  55362. loop: true,
  55363. autoUpdateTexture: true,
  55364. }; }
  55365. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55366. _this._createInternalTexture = function () {
  55367. if (_this._texture != null) {
  55368. return;
  55369. }
  55370. if (!_this._engine.needPOTTextures ||
  55371. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55372. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55373. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55374. }
  55375. else {
  55376. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55377. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55378. _this._generateMipMaps = false;
  55379. }
  55380. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55381. _this._texture.isReady = true;
  55382. _this._updateInternalTexture();
  55383. };
  55384. _this.reset = function () {
  55385. if (_this._texture == null) {
  55386. return;
  55387. }
  55388. _this._texture.dispose();
  55389. _this._texture = null;
  55390. };
  55391. _this._updateInternalTexture = function (e) {
  55392. if (_this._texture == null || !_this._texture.isReady) {
  55393. return;
  55394. }
  55395. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55396. return;
  55397. }
  55398. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55399. };
  55400. _this._engine = _this.getScene().getEngine();
  55401. _this._generateMipMaps = generateMipMaps;
  55402. _this._samplingMode = samplingMode;
  55403. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55404. _this.name = name || _this._getName(src);
  55405. _this.video = _this._getVideo(src);
  55406. if (settings.autoPlay !== undefined) {
  55407. _this.video.autoplay = settings.autoPlay;
  55408. }
  55409. if (settings.loop !== undefined) {
  55410. _this.video.loop = settings.loop;
  55411. }
  55412. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55413. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55414. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55415. _this.video.addEventListener("emptied", _this.reset);
  55416. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55417. _this._createInternalTexture();
  55418. }
  55419. return _this;
  55420. }
  55421. VideoTexture.prototype._getName = function (src) {
  55422. if (src instanceof HTMLVideoElement) {
  55423. return src.currentSrc;
  55424. }
  55425. if (typeof src === "object") {
  55426. return src.toString();
  55427. }
  55428. return src;
  55429. };
  55430. ;
  55431. VideoTexture.prototype._getVideo = function (src) {
  55432. if (src instanceof HTMLVideoElement) {
  55433. return src;
  55434. }
  55435. var video = document.createElement("video");
  55436. if (typeof src === "string") {
  55437. video.src = src;
  55438. }
  55439. else {
  55440. src.forEach(function (url) {
  55441. var source = document.createElement("source");
  55442. source.src = url;
  55443. video.appendChild(source);
  55444. });
  55445. }
  55446. return video;
  55447. };
  55448. ;
  55449. /**
  55450. * Internal method to initiate `update`.
  55451. */
  55452. VideoTexture.prototype._rebuild = function () {
  55453. this.update();
  55454. };
  55455. /**
  55456. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55457. */
  55458. VideoTexture.prototype.update = function () {
  55459. if (!this.autoUpdateTexture) {
  55460. // Expecting user to call `updateTexture` manually
  55461. return;
  55462. }
  55463. this.updateTexture(true);
  55464. };
  55465. /**
  55466. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55467. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55468. */
  55469. VideoTexture.prototype.updateTexture = function (isVisible) {
  55470. if (!isVisible) {
  55471. return;
  55472. }
  55473. if (this.video.paused) {
  55474. return;
  55475. }
  55476. this._updateInternalTexture();
  55477. };
  55478. /**
  55479. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55480. * @param url New url.
  55481. */
  55482. VideoTexture.prototype.updateURL = function (url) {
  55483. this.video.src = url;
  55484. };
  55485. VideoTexture.prototype.dispose = function () {
  55486. _super.prototype.dispose.call(this);
  55487. this.video.removeEventListener("canplay", this._createInternalTexture);
  55488. this.video.removeEventListener("paused", this._updateInternalTexture);
  55489. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55490. this.video.removeEventListener("emptied", this.reset);
  55491. };
  55492. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55493. var video = document.createElement("video");
  55494. var constraintsDeviceId;
  55495. if (constraints && constraints.deviceId) {
  55496. constraintsDeviceId = {
  55497. exact: constraints.deviceId,
  55498. };
  55499. }
  55500. navigator.getUserMedia =
  55501. navigator.getUserMedia ||
  55502. navigator.webkitGetUserMedia ||
  55503. navigator.mozGetUserMedia ||
  55504. navigator.msGetUserMedia;
  55505. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55506. if (navigator.getUserMedia) {
  55507. navigator.getUserMedia({
  55508. video: {
  55509. deviceId: constraintsDeviceId,
  55510. width: {
  55511. min: (constraints && constraints.minWidth) || 256,
  55512. max: (constraints && constraints.maxWidth) || 640,
  55513. },
  55514. height: {
  55515. min: (constraints && constraints.minHeight) || 256,
  55516. max: (constraints && constraints.maxHeight) || 480,
  55517. },
  55518. },
  55519. }, function (stream) {
  55520. if (video.mozSrcObject !== undefined) {
  55521. // hack for Firefox < 19
  55522. video.mozSrcObject = stream;
  55523. }
  55524. else {
  55525. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55526. }
  55527. video.play();
  55528. if (onReady) {
  55529. onReady(new VideoTexture("video", video, scene, true, true));
  55530. }
  55531. }, function (e) {
  55532. BABYLON.Tools.Error(e.name);
  55533. });
  55534. }
  55535. };
  55536. return VideoTexture;
  55537. }(BABYLON.Texture));
  55538. BABYLON.VideoTexture = VideoTexture;
  55539. })(BABYLON || (BABYLON = {}));
  55540. //# sourceMappingURL=babylon.videoTexture.js.map
  55541. var BABYLON;
  55542. (function (BABYLON) {
  55543. var RawTexture = /** @class */ (function (_super) {
  55544. __extends(RawTexture, _super);
  55545. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55546. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55547. if (invertY === void 0) { invertY = false; }
  55548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55549. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55550. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55551. _this.format = format;
  55552. _this._engine = scene.getEngine();
  55553. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55554. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55555. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55556. return _this;
  55557. }
  55558. RawTexture.prototype.update = function (data) {
  55559. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55560. };
  55561. // Statics
  55562. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55563. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55564. if (invertY === void 0) { invertY = false; }
  55565. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55566. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55567. };
  55568. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55569. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55570. if (invertY === void 0) { invertY = false; }
  55571. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55572. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55573. };
  55574. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55575. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55576. if (invertY === void 0) { invertY = false; }
  55577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55578. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55579. };
  55580. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55581. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55582. if (invertY === void 0) { invertY = false; }
  55583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55584. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55585. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55586. };
  55587. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55588. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55589. if (invertY === void 0) { invertY = false; }
  55590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55591. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55592. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55593. };
  55594. return RawTexture;
  55595. }(BABYLON.Texture));
  55596. BABYLON.RawTexture = RawTexture;
  55597. })(BABYLON || (BABYLON = {}));
  55598. //# sourceMappingURL=babylon.rawTexture.js.map
  55599. var BABYLON;
  55600. (function (BABYLON) {
  55601. var PostProcess = /** @class */ (function () {
  55602. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55604. if (defines === void 0) { defines = null; }
  55605. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55606. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55607. if (blockCompilation === void 0) { blockCompilation = false; }
  55608. this.name = name;
  55609. this.width = -1;
  55610. this.height = -1;
  55611. this.autoClear = true;
  55612. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55613. this.animations = new Array();
  55614. /*
  55615. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55616. Can only be used on a single postprocess or on the last one of a chain.
  55617. */
  55618. this.enablePixelPerfectMode = false;
  55619. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55620. this.alwaysForcePOT = false;
  55621. this.samples = 1;
  55622. this.adaptScaleToCurrentViewport = false;
  55623. this._reusable = false;
  55624. this._textures = new BABYLON.SmartArray(2);
  55625. this._currentRenderTextureInd = 0;
  55626. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55627. this._texelSize = BABYLON.Vector2.Zero();
  55628. // Events
  55629. /**
  55630. * An event triggered when the postprocess is activated.
  55631. * @type {BABYLON.Observable}
  55632. */
  55633. this.onActivateObservable = new BABYLON.Observable();
  55634. /**
  55635. * An event triggered when the postprocess changes its size.
  55636. * @type {BABYLON.Observable}
  55637. */
  55638. this.onSizeChangedObservable = new BABYLON.Observable();
  55639. /**
  55640. * An event triggered when the postprocess applies its effect.
  55641. * @type {BABYLON.Observable}
  55642. */
  55643. this.onApplyObservable = new BABYLON.Observable();
  55644. /**
  55645. * An event triggered before rendering the postprocess
  55646. * @type {BABYLON.Observable}
  55647. */
  55648. this.onBeforeRenderObservable = new BABYLON.Observable();
  55649. /**
  55650. * An event triggered after rendering the postprocess
  55651. * @type {BABYLON.Observable}
  55652. */
  55653. this.onAfterRenderObservable = new BABYLON.Observable();
  55654. if (camera != null) {
  55655. this._camera = camera;
  55656. this._scene = camera.getScene();
  55657. camera.attachPostProcess(this);
  55658. this._engine = this._scene.getEngine();
  55659. this._scene.postProcesses.push(this);
  55660. }
  55661. else if (engine) {
  55662. this._engine = engine;
  55663. this._engine.postProcesses.push(this);
  55664. }
  55665. this._options = options;
  55666. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55667. this._reusable = reusable || false;
  55668. this._textureType = textureType;
  55669. this._samplers = samplers || [];
  55670. this._samplers.push("textureSampler");
  55671. this._fragmentUrl = fragmentUrl;
  55672. this._vertexUrl = vertexUrl;
  55673. this._parameters = parameters || [];
  55674. this._parameters.push("scale");
  55675. this._indexParameters = indexParameters;
  55676. if (!blockCompilation) {
  55677. this.updateEffect(defines);
  55678. }
  55679. }
  55680. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55681. set: function (callback) {
  55682. if (this._onActivateObserver) {
  55683. this.onActivateObservable.remove(this._onActivateObserver);
  55684. }
  55685. if (callback) {
  55686. this._onActivateObserver = this.onActivateObservable.add(callback);
  55687. }
  55688. },
  55689. enumerable: true,
  55690. configurable: true
  55691. });
  55692. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55693. set: function (callback) {
  55694. if (this._onSizeChangedObserver) {
  55695. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55696. }
  55697. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55698. },
  55699. enumerable: true,
  55700. configurable: true
  55701. });
  55702. Object.defineProperty(PostProcess.prototype, "onApply", {
  55703. set: function (callback) {
  55704. if (this._onApplyObserver) {
  55705. this.onApplyObservable.remove(this._onApplyObserver);
  55706. }
  55707. this._onApplyObserver = this.onApplyObservable.add(callback);
  55708. },
  55709. enumerable: true,
  55710. configurable: true
  55711. });
  55712. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55713. set: function (callback) {
  55714. if (this._onBeforeRenderObserver) {
  55715. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55716. }
  55717. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55718. },
  55719. enumerable: true,
  55720. configurable: true
  55721. });
  55722. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55723. set: function (callback) {
  55724. if (this._onAfterRenderObserver) {
  55725. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55726. }
  55727. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55728. },
  55729. enumerable: true,
  55730. configurable: true
  55731. });
  55732. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55733. get: function () {
  55734. return this._textures.data[this._currentRenderTextureInd];
  55735. },
  55736. set: function (value) {
  55737. this._forcedOutputTexture = value;
  55738. },
  55739. enumerable: true,
  55740. configurable: true
  55741. });
  55742. PostProcess.prototype.getCamera = function () {
  55743. return this._camera;
  55744. };
  55745. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55746. get: function () {
  55747. if (this._shareOutputWithPostProcess) {
  55748. return this._shareOutputWithPostProcess.texelSize;
  55749. }
  55750. if (this._forcedOutputTexture) {
  55751. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55752. }
  55753. return this._texelSize;
  55754. },
  55755. enumerable: true,
  55756. configurable: true
  55757. });
  55758. PostProcess.prototype.getEngine = function () {
  55759. return this._engine;
  55760. };
  55761. PostProcess.prototype.getEffect = function () {
  55762. return this._effect;
  55763. };
  55764. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55765. this._disposeTextures();
  55766. this._shareOutputWithPostProcess = postProcess;
  55767. return this;
  55768. };
  55769. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55770. if (defines === void 0) { defines = null; }
  55771. if (uniforms === void 0) { uniforms = null; }
  55772. if (samplers === void 0) { samplers = null; }
  55773. 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);
  55774. };
  55775. PostProcess.prototype.isReusable = function () {
  55776. return this._reusable;
  55777. };
  55778. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55779. PostProcess.prototype.markTextureDirty = function () {
  55780. this.width = -1;
  55781. };
  55782. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55783. var _this = this;
  55784. if (sourceTexture === void 0) { sourceTexture = null; }
  55785. camera = camera || this._camera;
  55786. var scene = camera.getScene();
  55787. var engine = scene.getEngine();
  55788. var maxSize = engine.getCaps().maxTextureSize;
  55789. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55790. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55791. var desiredWidth = (this._options.width || requiredWidth);
  55792. var desiredHeight = this._options.height || requiredHeight;
  55793. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55794. if (this.adaptScaleToCurrentViewport) {
  55795. var currentViewport = engine.currentViewport;
  55796. if (currentViewport) {
  55797. desiredWidth *= currentViewport.width;
  55798. desiredHeight *= currentViewport.height;
  55799. }
  55800. }
  55801. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55802. if (!this._options.width) {
  55803. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55804. }
  55805. if (!this._options.height) {
  55806. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55807. }
  55808. }
  55809. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  55810. if (this._textures.length > 0) {
  55811. for (var i = 0; i < this._textures.length; i++) {
  55812. this._engine._releaseTexture(this._textures.data[i]);
  55813. }
  55814. this._textures.reset();
  55815. }
  55816. this.width = desiredWidth;
  55817. this.height = desiredHeight;
  55818. var textureSize = { width: this.width, height: this.height };
  55819. var textureOptions = {
  55820. generateMipMaps: false,
  55821. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  55822. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  55823. samplingMode: this.renderTargetSamplingMode,
  55824. type: this._textureType
  55825. };
  55826. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55827. if (this._reusable) {
  55828. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55829. }
  55830. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  55831. this.onSizeChangedObservable.notifyObservers(this);
  55832. }
  55833. this._textures.forEach(function (texture) {
  55834. if (texture.samples !== _this.samples) {
  55835. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  55836. }
  55837. });
  55838. }
  55839. var target;
  55840. if (this._shareOutputWithPostProcess) {
  55841. target = this._shareOutputWithPostProcess.outputTexture;
  55842. }
  55843. else if (this._forcedOutputTexture) {
  55844. target = this._forcedOutputTexture;
  55845. this.width = this._forcedOutputTexture.width;
  55846. this.height = this._forcedOutputTexture.height;
  55847. }
  55848. else {
  55849. target = this.outputTexture;
  55850. }
  55851. if (this.enablePixelPerfectMode) {
  55852. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  55853. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  55854. }
  55855. else {
  55856. this._scaleRatio.copyFromFloats(1, 1);
  55857. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  55858. }
  55859. this.onActivateObservable.notifyObservers(camera);
  55860. // Clear
  55861. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  55862. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  55863. }
  55864. if (this._reusable) {
  55865. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  55866. }
  55867. };
  55868. Object.defineProperty(PostProcess.prototype, "isSupported", {
  55869. get: function () {
  55870. return this._effect.isSupported;
  55871. },
  55872. enumerable: true,
  55873. configurable: true
  55874. });
  55875. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  55876. get: function () {
  55877. if (this._shareOutputWithPostProcess) {
  55878. return this._shareOutputWithPostProcess.aspectRatio;
  55879. }
  55880. if (this._forcedOutputTexture) {
  55881. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  55882. }
  55883. return this.width / this.height;
  55884. },
  55885. enumerable: true,
  55886. configurable: true
  55887. });
  55888. /**
  55889. * Get a value indicating if the post-process is ready to be used
  55890. * @returns true if the post-process is ready (shader is compiled)
  55891. */
  55892. PostProcess.prototype.isReady = function () {
  55893. return this._effect && this._effect.isReady();
  55894. };
  55895. PostProcess.prototype.apply = function () {
  55896. // Check
  55897. if (!this._effect || !this._effect.isReady())
  55898. return null;
  55899. // States
  55900. this._engine.enableEffect(this._effect);
  55901. this._engine.setState(false);
  55902. this._engine.setDepthBuffer(false);
  55903. this._engine.setDepthWrite(false);
  55904. // Alpha
  55905. this._engine.setAlphaMode(this.alphaMode);
  55906. if (this.alphaConstants) {
  55907. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  55908. }
  55909. // Texture
  55910. var source;
  55911. if (this._shareOutputWithPostProcess) {
  55912. source = this._shareOutputWithPostProcess.outputTexture;
  55913. }
  55914. else if (this._forcedOutputTexture) {
  55915. source = this._forcedOutputTexture;
  55916. }
  55917. else {
  55918. source = this.outputTexture;
  55919. }
  55920. this._effect._bindTexture("textureSampler", source);
  55921. // Parameters
  55922. this._effect.setVector2("scale", this._scaleRatio);
  55923. this.onApplyObservable.notifyObservers(this._effect);
  55924. return this._effect;
  55925. };
  55926. PostProcess.prototype._disposeTextures = function () {
  55927. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  55928. return;
  55929. }
  55930. if (this._textures.length > 0) {
  55931. for (var i = 0; i < this._textures.length; i++) {
  55932. this._engine._releaseTexture(this._textures.data[i]);
  55933. }
  55934. }
  55935. this._textures.dispose();
  55936. };
  55937. PostProcess.prototype.dispose = function (camera) {
  55938. camera = camera || this._camera;
  55939. this._disposeTextures();
  55940. if (this._scene) {
  55941. var index_1 = this._scene.postProcesses.indexOf(this);
  55942. if (index_1 !== -1) {
  55943. this._scene.postProcesses.splice(index_1, 1);
  55944. }
  55945. }
  55946. else {
  55947. var index_2 = this._engine.postProcesses.indexOf(this);
  55948. if (index_2 !== -1) {
  55949. this._engine.postProcesses.splice(index_2, 1);
  55950. }
  55951. }
  55952. if (!camera) {
  55953. return;
  55954. }
  55955. camera.detachPostProcess(this);
  55956. var index = camera._postProcesses.indexOf(this);
  55957. if (index === 0 && camera._postProcesses.length > 0) {
  55958. this._camera._postProcesses[0].markTextureDirty();
  55959. }
  55960. this.onActivateObservable.clear();
  55961. this.onAfterRenderObservable.clear();
  55962. this.onApplyObservable.clear();
  55963. this.onBeforeRenderObservable.clear();
  55964. this.onSizeChangedObservable.clear();
  55965. };
  55966. return PostProcess;
  55967. }());
  55968. BABYLON.PostProcess = PostProcess;
  55969. })(BABYLON || (BABYLON = {}));
  55970. //# sourceMappingURL=babylon.postProcess.js.map
  55971. var BABYLON;
  55972. (function (BABYLON) {
  55973. var PassPostProcess = /** @class */ (function (_super) {
  55974. __extends(PassPostProcess, _super);
  55975. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55976. if (camera === void 0) { camera = null; }
  55977. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55978. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55979. }
  55980. return PassPostProcess;
  55981. }(BABYLON.PostProcess));
  55982. BABYLON.PassPostProcess = PassPostProcess;
  55983. })(BABYLON || (BABYLON = {}));
  55984. //# sourceMappingURL=babylon.passPostProcess.js.map
  55985. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55986. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55987. s = arguments[i];
  55988. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55989. t[p] = s[p];
  55990. }
  55991. return t;
  55992. };
  55993. var BABYLON;
  55994. (function (BABYLON) {
  55995. /**
  55996. * Default implementation of @see IShadowGenerator.
  55997. * This is the main object responsible of generating shadows in the framework.
  55998. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  55999. */
  56000. var ShadowGenerator = /** @class */ (function () {
  56001. /**
  56002. * Creates a ShadowGenerator object.
  56003. * A ShadowGenerator is the required tool to use the shadows.
  56004. * Each light casting shadows needs to use its own ShadowGenerator.
  56005. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  56006. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  56007. * @param light The light object generating the shadows.
  56008. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  56009. */
  56010. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  56011. this._bias = 0.00005;
  56012. this._blurBoxOffset = 1;
  56013. this._blurScale = 2;
  56014. this._blurKernel = 1;
  56015. this._useKernelBlur = false;
  56016. this._filter = ShadowGenerator.FILTER_NONE;
  56017. this._darkness = 0;
  56018. this._transparencyShadow = false;
  56019. /**
  56020. * Controls the extent to which the shadows fade out at the edge of the frustum
  56021. * Used only by directionals and spots
  56022. */
  56023. this.frustumEdgeFalloff = 0;
  56024. /**
  56025. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  56026. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  56027. * It might on the other hand introduce peter panning.
  56028. */
  56029. this.forceBackFacesOnly = false;
  56030. this._lightDirection = BABYLON.Vector3.Zero();
  56031. this._viewMatrix = BABYLON.Matrix.Zero();
  56032. this._projectionMatrix = BABYLON.Matrix.Zero();
  56033. this._transformMatrix = BABYLON.Matrix.Zero();
  56034. this._currentFaceIndex = 0;
  56035. this._currentFaceIndexCache = 0;
  56036. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  56037. this._mapSize = mapSize;
  56038. this._light = light;
  56039. this._scene = light.getScene();
  56040. light._shadowGenerator = this;
  56041. // Texture type fallback from float to int if not supported.
  56042. var caps = this._scene.getEngine().getCaps();
  56043. if (!useFullFloatFirst) {
  56044. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56045. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56046. }
  56047. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56048. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56049. }
  56050. else {
  56051. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56052. }
  56053. }
  56054. else {
  56055. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56056. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56057. }
  56058. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56059. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56060. }
  56061. else {
  56062. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56063. }
  56064. }
  56065. this._initializeGenerator();
  56066. }
  56067. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  56068. /**
  56069. * Shadow generator mode None: no filtering applied.
  56070. */
  56071. get: function () {
  56072. return ShadowGenerator._FILTER_NONE;
  56073. },
  56074. enumerable: true,
  56075. configurable: true
  56076. });
  56077. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  56078. /**
  56079. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  56080. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  56081. */
  56082. get: function () {
  56083. return ShadowGenerator._FILTER_POISSONSAMPLING;
  56084. },
  56085. enumerable: true,
  56086. configurable: true
  56087. });
  56088. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  56089. /**
  56090. * Shadow generator mode ESM: Exponential Shadow Mapping.
  56091. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56092. */
  56093. get: function () {
  56094. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  56095. },
  56096. enumerable: true,
  56097. configurable: true
  56098. });
  56099. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  56100. /**
  56101. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  56102. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56103. */
  56104. get: function () {
  56105. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  56106. },
  56107. enumerable: true,
  56108. configurable: true
  56109. });
  56110. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  56111. /**
  56112. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  56113. * edge artifacts on steep falloff.
  56114. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56115. */
  56116. get: function () {
  56117. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56118. },
  56119. enumerable: true,
  56120. configurable: true
  56121. });
  56122. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  56123. /**
  56124. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  56125. * edge artifacts on steep falloff.
  56126. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56127. */
  56128. get: function () {
  56129. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56130. },
  56131. enumerable: true,
  56132. configurable: true
  56133. });
  56134. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  56135. /**
  56136. * Gets the bias: offset applied on the depth preventing acnea.
  56137. */
  56138. get: function () {
  56139. return this._bias;
  56140. },
  56141. /**
  56142. * Sets the bias: offset applied on the depth preventing acnea.
  56143. */
  56144. set: function (bias) {
  56145. this._bias = bias;
  56146. },
  56147. enumerable: true,
  56148. configurable: true
  56149. });
  56150. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  56151. /**
  56152. * Gets the blur box offset: offset applied during the blur pass.
  56153. * Only usefull if useKernelBlur = false
  56154. */
  56155. get: function () {
  56156. return this._blurBoxOffset;
  56157. },
  56158. /**
  56159. * Sets the blur box offset: offset applied during the blur pass.
  56160. * Only usefull if useKernelBlur = false
  56161. */
  56162. set: function (value) {
  56163. if (this._blurBoxOffset === value) {
  56164. return;
  56165. }
  56166. this._blurBoxOffset = value;
  56167. this._disposeBlurPostProcesses();
  56168. },
  56169. enumerable: true,
  56170. configurable: true
  56171. });
  56172. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  56173. /**
  56174. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  56175. * 2 means half of the size.
  56176. */
  56177. get: function () {
  56178. return this._blurScale;
  56179. },
  56180. /**
  56181. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  56182. * 2 means half of the size.
  56183. */
  56184. set: function (value) {
  56185. if (this._blurScale === value) {
  56186. return;
  56187. }
  56188. this._blurScale = value;
  56189. this._disposeBlurPostProcesses();
  56190. },
  56191. enumerable: true,
  56192. configurable: true
  56193. });
  56194. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  56195. /**
  56196. * Gets the blur kernel: kernel size of the blur pass.
  56197. * Only usefull if useKernelBlur = true
  56198. */
  56199. get: function () {
  56200. return this._blurKernel;
  56201. },
  56202. /**
  56203. * Sets the blur kernel: kernel size of the blur pass.
  56204. * Only usefull if useKernelBlur = true
  56205. */
  56206. set: function (value) {
  56207. if (this._blurKernel === value) {
  56208. return;
  56209. }
  56210. this._blurKernel = value;
  56211. this._disposeBlurPostProcesses();
  56212. },
  56213. enumerable: true,
  56214. configurable: true
  56215. });
  56216. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  56217. /**
  56218. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  56219. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56220. */
  56221. get: function () {
  56222. return this._useKernelBlur;
  56223. },
  56224. /**
  56225. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  56226. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56227. */
  56228. set: function (value) {
  56229. if (this._useKernelBlur === value) {
  56230. return;
  56231. }
  56232. this._useKernelBlur = value;
  56233. this._disposeBlurPostProcesses();
  56234. },
  56235. enumerable: true,
  56236. configurable: true
  56237. });
  56238. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  56239. /**
  56240. * Gets the depth scale used in ESM mode.
  56241. */
  56242. get: function () {
  56243. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  56244. },
  56245. /**
  56246. * Sets the depth scale used in ESM mode.
  56247. * This can override the scale stored on the light.
  56248. */
  56249. set: function (value) {
  56250. this._depthScale = value;
  56251. },
  56252. enumerable: true,
  56253. configurable: true
  56254. });
  56255. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  56256. /**
  56257. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  56258. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56259. */
  56260. get: function () {
  56261. return this._filter;
  56262. },
  56263. /**
  56264. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  56265. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56266. */
  56267. set: function (value) {
  56268. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  56269. if (this._light.needCube()) {
  56270. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56271. this.useExponentialShadowMap = true;
  56272. return;
  56273. }
  56274. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56275. this.useCloseExponentialShadowMap = true;
  56276. return;
  56277. }
  56278. }
  56279. if (this._filter === value) {
  56280. return;
  56281. }
  56282. this._filter = value;
  56283. this._disposeBlurPostProcesses();
  56284. this._applyFilterValues();
  56285. this._light._markMeshesAsLightDirty();
  56286. },
  56287. enumerable: true,
  56288. configurable: true
  56289. });
  56290. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  56291. /**
  56292. * Gets if the current filter is set to Poisson Sampling aka PCF.
  56293. */
  56294. get: function () {
  56295. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  56296. },
  56297. /**
  56298. * Sets the current filter to Poisson Sampling aka PCF.
  56299. */
  56300. set: function (value) {
  56301. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  56302. return;
  56303. }
  56304. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  56305. },
  56306. enumerable: true,
  56307. configurable: true
  56308. });
  56309. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  56310. /**
  56311. * Gets if the current filter is set to VSM.
  56312. * DEPRECATED. Should use useExponentialShadowMap instead.
  56313. */
  56314. get: function () {
  56315. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56316. return this.useExponentialShadowMap;
  56317. },
  56318. /**
  56319. * Sets the current filter is to VSM.
  56320. * DEPRECATED. Should use useExponentialShadowMap instead.
  56321. */
  56322. set: function (value) {
  56323. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56324. this.useExponentialShadowMap = value;
  56325. },
  56326. enumerable: true,
  56327. configurable: true
  56328. });
  56329. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  56330. /**
  56331. * Gets if the current filter is set to blurred VSM.
  56332. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56333. */
  56334. get: function () {
  56335. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56336. return this.useBlurExponentialShadowMap;
  56337. },
  56338. /**
  56339. * Sets the current filter is to blurred VSM.
  56340. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56341. */
  56342. set: function (value) {
  56343. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56344. this.useBlurExponentialShadowMap = value;
  56345. },
  56346. enumerable: true,
  56347. configurable: true
  56348. });
  56349. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  56350. /**
  56351. * Gets if the current filter is set to ESM.
  56352. */
  56353. get: function () {
  56354. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  56355. },
  56356. /**
  56357. * Sets the current filter is to ESM.
  56358. */
  56359. set: function (value) {
  56360. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  56361. return;
  56362. }
  56363. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56364. },
  56365. enumerable: true,
  56366. configurable: true
  56367. });
  56368. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  56369. /**
  56370. * Gets if the current filter is set to filtered ESM.
  56371. */
  56372. get: function () {
  56373. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  56374. },
  56375. /**
  56376. * Gets if the current filter is set to filtered ESM.
  56377. */
  56378. set: function (value) {
  56379. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56380. return;
  56381. }
  56382. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56383. },
  56384. enumerable: true,
  56385. configurable: true
  56386. });
  56387. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  56388. /**
  56389. * Gets if the current filter is set to "close ESM" (using the inverse of the
  56390. * exponential to prevent steep falloff artifacts).
  56391. */
  56392. get: function () {
  56393. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56394. },
  56395. /**
  56396. * Sets the current filter to "close ESM" (using the inverse of the
  56397. * exponential to prevent steep falloff artifacts).
  56398. */
  56399. set: function (value) {
  56400. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  56401. return;
  56402. }
  56403. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56404. },
  56405. enumerable: true,
  56406. configurable: true
  56407. });
  56408. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  56409. /**
  56410. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  56411. * exponential to prevent steep falloff artifacts).
  56412. */
  56413. get: function () {
  56414. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56415. },
  56416. /**
  56417. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  56418. * exponential to prevent steep falloff artifacts).
  56419. */
  56420. set: function (value) {
  56421. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56422. return;
  56423. }
  56424. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56425. },
  56426. enumerable: true,
  56427. configurable: true
  56428. });
  56429. /**
  56430. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  56431. * 0 means strongest and 1 would means no shadow.
  56432. * @returns the darkness.
  56433. */
  56434. ShadowGenerator.prototype.getDarkness = function () {
  56435. return this._darkness;
  56436. };
  56437. /**
  56438. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  56439. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  56440. * @returns the shadow generator allowing fluent coding.
  56441. */
  56442. ShadowGenerator.prototype.setDarkness = function (darkness) {
  56443. if (darkness >= 1.0)
  56444. this._darkness = 1.0;
  56445. else if (darkness <= 0.0)
  56446. this._darkness = 0.0;
  56447. else
  56448. this._darkness = darkness;
  56449. return this;
  56450. };
  56451. /**
  56452. * Sets the ability to have transparent shadow (boolean).
  56453. * @param transparent True if transparent else False
  56454. * @returns the shadow generator allowing fluent coding
  56455. */
  56456. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  56457. this._transparencyShadow = transparent;
  56458. return this;
  56459. };
  56460. /**
  56461. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  56462. * @returns The render target texture if present otherwise, null
  56463. */
  56464. ShadowGenerator.prototype.getShadowMap = function () {
  56465. return this._shadowMap;
  56466. };
  56467. /**
  56468. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  56469. * @returns The render target texture if the shadow map is present otherwise, null
  56470. */
  56471. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  56472. if (this._shadowMap2) {
  56473. return this._shadowMap2;
  56474. }
  56475. return this._shadowMap;
  56476. };
  56477. /**
  56478. * Helper function to add a mesh and its descendants to the list of shadow casters.
  56479. * @param mesh Mesh to add
  56480. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  56481. * @returns the Shadow Generator itself
  56482. */
  56483. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  56484. if (includeDescendants === void 0) { includeDescendants = true; }
  56485. if (!this._shadowMap) {
  56486. return this;
  56487. }
  56488. if (!this._shadowMap.renderList) {
  56489. this._shadowMap.renderList = [];
  56490. }
  56491. this._shadowMap.renderList.push(mesh);
  56492. if (includeDescendants) {
  56493. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  56494. }
  56495. return this;
  56496. var _a;
  56497. };
  56498. /**
  56499. * Helper function to remove a mesh and its descendants from the list of shadow casters
  56500. * @param mesh Mesh to remove
  56501. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  56502. * @returns the Shadow Generator itself
  56503. */
  56504. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  56505. if (includeDescendants === void 0) { includeDescendants = true; }
  56506. if (!this._shadowMap || !this._shadowMap.renderList) {
  56507. return this;
  56508. }
  56509. var index = this._shadowMap.renderList.indexOf(mesh);
  56510. if (index !== -1) {
  56511. this._shadowMap.renderList.splice(index, 1);
  56512. }
  56513. if (includeDescendants) {
  56514. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  56515. var child = _a[_i];
  56516. this.removeShadowCaster(child);
  56517. }
  56518. }
  56519. return this;
  56520. };
  56521. /**
  56522. * Returns the associated light object.
  56523. * @returns the light generating the shadow
  56524. */
  56525. ShadowGenerator.prototype.getLight = function () {
  56526. return this._light;
  56527. };
  56528. ShadowGenerator.prototype._initializeGenerator = function () {
  56529. this._light._markMeshesAsLightDirty();
  56530. this._initializeShadowMap();
  56531. };
  56532. ShadowGenerator.prototype._initializeShadowMap = function () {
  56533. var _this = this;
  56534. // Render target
  56535. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  56536. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56537. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56538. this._shadowMap.anisotropicFilteringLevel = 1;
  56539. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56540. this._shadowMap.renderParticles = false;
  56541. this._shadowMap.ignoreCameraViewport = true;
  56542. // Record Face Index before render.
  56543. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  56544. _this._currentFaceIndex = faceIndex;
  56545. });
  56546. // Custom render function.
  56547. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  56548. // Blur if required afer render.
  56549. this._shadowMap.onAfterUnbindObservable.add(function () {
  56550. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  56551. return;
  56552. }
  56553. var shadowMap = _this.getShadowMapForRendering();
  56554. if (shadowMap) {
  56555. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  56556. }
  56557. });
  56558. // Clear according to the chosen filter.
  56559. this._shadowMap.onClearObservable.add(function (engine) {
  56560. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  56561. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  56562. }
  56563. else {
  56564. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56565. }
  56566. });
  56567. };
  56568. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  56569. var _this = this;
  56570. var engine = this._scene.getEngine();
  56571. var targetSize = this._mapSize / this.blurScale;
  56572. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  56573. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  56574. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56575. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56576. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56577. }
  56578. if (this.useKernelBlur) {
  56579. 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);
  56580. this._kernelBlurXPostprocess.width = targetSize;
  56581. this._kernelBlurXPostprocess.height = targetSize;
  56582. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  56583. effect.setTexture("textureSampler", _this._shadowMap);
  56584. });
  56585. 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);
  56586. this._kernelBlurXPostprocess.autoClear = false;
  56587. this._kernelBlurYPostprocess.autoClear = false;
  56588. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56589. this._kernelBlurXPostprocess.packedFloat = true;
  56590. this._kernelBlurYPostprocess.packedFloat = true;
  56591. }
  56592. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  56593. }
  56594. else {
  56595. 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);
  56596. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  56597. effect.setFloat2("screenSize", targetSize, targetSize);
  56598. effect.setTexture("textureSampler", _this._shadowMap);
  56599. });
  56600. this._boxBlurPostprocess.autoClear = false;
  56601. this._blurPostProcesses = [this._boxBlurPostprocess];
  56602. }
  56603. };
  56604. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56605. var index;
  56606. var engine = this._scene.getEngine();
  56607. if (depthOnlySubMeshes.length) {
  56608. engine.setColorWrite(false);
  56609. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56610. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  56611. }
  56612. engine.setColorWrite(true);
  56613. }
  56614. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56615. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  56616. }
  56617. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56618. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  56619. }
  56620. if (this._transparencyShadow) {
  56621. for (index = 0; index < transparentSubMeshes.length; index++) {
  56622. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  56623. }
  56624. }
  56625. };
  56626. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  56627. var _this = this;
  56628. var mesh = subMesh.getRenderingMesh();
  56629. var scene = this._scene;
  56630. var engine = scene.getEngine();
  56631. var material = subMesh.getMaterial();
  56632. if (!material) {
  56633. return;
  56634. }
  56635. // Culling
  56636. engine.setState(material.backFaceCulling);
  56637. // Managing instances
  56638. var batch = mesh._getInstancesRenderList(subMesh._id);
  56639. if (batch.mustReturn) {
  56640. return;
  56641. }
  56642. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  56643. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  56644. engine.enableEffect(this._effect);
  56645. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  56646. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  56647. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  56648. this._effect.setVector3("lightPosition", this.getLight().position);
  56649. if (scene.activeCamera) {
  56650. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  56651. }
  56652. // Alpha test
  56653. if (material && material.needAlphaTesting()) {
  56654. var alphaTexture = material.getAlphaTestTexture();
  56655. if (alphaTexture) {
  56656. this._effect.setTexture("diffuseSampler", alphaTexture);
  56657. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  56658. }
  56659. }
  56660. // Bones
  56661. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56662. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  56663. }
  56664. if (this.forceBackFacesOnly) {
  56665. engine.setState(true, 0, false, true);
  56666. }
  56667. // Draw
  56668. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56669. if (this.forceBackFacesOnly) {
  56670. engine.setState(true, 0, false, false);
  56671. }
  56672. }
  56673. else {
  56674. // Need to reset refresh rate of the shadowMap
  56675. if (this._shadowMap) {
  56676. this._shadowMap.resetRefreshCounter();
  56677. }
  56678. }
  56679. };
  56680. ShadowGenerator.prototype._applyFilterValues = function () {
  56681. if (!this._shadowMap) {
  56682. return;
  56683. }
  56684. if (this.filter === ShadowGenerator.FILTER_NONE) {
  56685. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56686. }
  56687. else {
  56688. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56689. }
  56690. };
  56691. /**
  56692. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  56693. * @param onCompiled Callback triggered at the and of the effects compilation
  56694. * @param options Sets of optional options forcing the compilation with different modes
  56695. */
  56696. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  56697. var _this = this;
  56698. var localOptions = __assign({ useInstances: false }, options);
  56699. var shadowMap = this.getShadowMap();
  56700. if (!shadowMap) {
  56701. if (onCompiled) {
  56702. onCompiled(this);
  56703. }
  56704. return;
  56705. }
  56706. var renderList = shadowMap.renderList;
  56707. if (!renderList) {
  56708. if (onCompiled) {
  56709. onCompiled(this);
  56710. }
  56711. return;
  56712. }
  56713. var subMeshes = new Array();
  56714. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  56715. var mesh = renderList_1[_i];
  56716. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  56717. }
  56718. if (subMeshes.length === 0) {
  56719. if (onCompiled) {
  56720. onCompiled(this);
  56721. }
  56722. return;
  56723. }
  56724. var currentIndex = 0;
  56725. var checkReady = function () {
  56726. if (!_this._scene || !_this._scene.getEngine()) {
  56727. return;
  56728. }
  56729. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  56730. currentIndex++;
  56731. if (currentIndex >= subMeshes.length) {
  56732. if (onCompiled) {
  56733. onCompiled(_this);
  56734. }
  56735. return;
  56736. }
  56737. }
  56738. setTimeout(checkReady, 16);
  56739. };
  56740. checkReady();
  56741. };
  56742. /**
  56743. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  56744. * @param subMesh The submesh we want to render in the shadow map
  56745. * @param useInstances Defines wether will draw in the map using instances
  56746. * @returns true if ready otherwise, false
  56747. */
  56748. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  56749. var defines = [];
  56750. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56751. defines.push("#define FLOAT");
  56752. }
  56753. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56754. defines.push("#define ESM");
  56755. }
  56756. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56757. var mesh = subMesh.getMesh();
  56758. var material = subMesh.getMaterial();
  56759. // Alpha test
  56760. if (material && material.needAlphaTesting()) {
  56761. var alphaTexture = material.getAlphaTestTexture();
  56762. if (alphaTexture) {
  56763. defines.push("#define ALPHATEST");
  56764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56765. attribs.push(BABYLON.VertexBuffer.UVKind);
  56766. defines.push("#define UV1");
  56767. }
  56768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56769. if (alphaTexture.coordinatesIndex === 1) {
  56770. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56771. defines.push("#define UV2");
  56772. }
  56773. }
  56774. }
  56775. }
  56776. // Bones
  56777. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56778. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56779. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56780. if (mesh.numBoneInfluencers > 4) {
  56781. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56782. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56783. }
  56784. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56785. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56786. }
  56787. else {
  56788. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56789. }
  56790. // Instances
  56791. if (useInstances) {
  56792. defines.push("#define INSTANCES");
  56793. attribs.push("world0");
  56794. attribs.push("world1");
  56795. attribs.push("world2");
  56796. attribs.push("world3");
  56797. }
  56798. // Get correct effect
  56799. var join = defines.join("\n");
  56800. if (this._cachedDefines !== join) {
  56801. this._cachedDefines = join;
  56802. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  56803. }
  56804. if (!this._effect.isReady()) {
  56805. return false;
  56806. }
  56807. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56808. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  56809. this._initializeBlurRTTAndPostProcesses();
  56810. }
  56811. }
  56812. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  56813. return false;
  56814. }
  56815. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  56816. return false;
  56817. }
  56818. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  56819. return false;
  56820. }
  56821. return true;
  56822. };
  56823. /**
  56824. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  56825. * @param defines Defines of the material we want to update
  56826. * @param lightIndex Index of the light in the enabled light list of the material
  56827. */
  56828. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  56829. var scene = this._scene;
  56830. var light = this._light;
  56831. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56832. return;
  56833. }
  56834. defines["SHADOW" + lightIndex] = true;
  56835. if (this.usePoissonSampling) {
  56836. defines["SHADOWPCF" + lightIndex] = true;
  56837. }
  56838. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56839. defines["SHADOWESM" + lightIndex] = true;
  56840. }
  56841. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56842. defines["SHADOWCLOSEESM" + lightIndex] = true;
  56843. }
  56844. if (light.needCube()) {
  56845. defines["SHADOWCUBE" + lightIndex] = true;
  56846. }
  56847. };
  56848. /**
  56849. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  56850. * defined in the generator but impacting the effect).
  56851. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  56852. * @param effect The effect we are binfing the information for
  56853. */
  56854. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  56855. var light = this._light;
  56856. var scene = this._scene;
  56857. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56858. return;
  56859. }
  56860. var camera = scene.activeCamera;
  56861. if (!camera) {
  56862. return;
  56863. }
  56864. var shadowMap = this.getShadowMap();
  56865. if (!shadowMap) {
  56866. return;
  56867. }
  56868. if (!light.needCube()) {
  56869. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  56870. }
  56871. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  56872. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  56873. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  56874. };
  56875. /**
  56876. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  56877. * (eq to shadow prjection matrix * light transform matrix)
  56878. * @returns The transform matrix used to create the shadow map
  56879. */
  56880. ShadowGenerator.prototype.getTransformMatrix = function () {
  56881. var scene = this._scene;
  56882. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  56883. return this._transformMatrix;
  56884. }
  56885. this._currentRenderID = scene.getRenderId();
  56886. this._currentFaceIndexCache = this._currentFaceIndex;
  56887. var lightPosition = this._light.position;
  56888. if (this._light.computeTransformedInformation()) {
  56889. lightPosition = this._light.transformedPosition;
  56890. }
  56891. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  56892. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  56893. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  56894. }
  56895. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  56896. this._cachedPosition = lightPosition.clone();
  56897. this._cachedDirection = this._lightDirection.clone();
  56898. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  56899. var shadowMap = this.getShadowMap();
  56900. if (shadowMap) {
  56901. var renderList = shadowMap.renderList;
  56902. if (renderList) {
  56903. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  56904. }
  56905. }
  56906. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  56907. }
  56908. return this._transformMatrix;
  56909. };
  56910. /**
  56911. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  56912. * Cube and 2D textures for instance.
  56913. */
  56914. ShadowGenerator.prototype.recreateShadowMap = function () {
  56915. var shadowMap = this._shadowMap;
  56916. if (!shadowMap) {
  56917. return;
  56918. }
  56919. // Track render list.
  56920. var renderList = shadowMap.renderList;
  56921. // Clean up existing data.
  56922. this._disposeRTTandPostProcesses();
  56923. // Reinitializes.
  56924. this._initializeGenerator();
  56925. // Reaffect the filter to ensure a correct fallback if necessary.
  56926. this.filter = this.filter;
  56927. // Reaffect the filter.
  56928. this._applyFilterValues();
  56929. // Reaffect Render List.
  56930. this._shadowMap.renderList = renderList;
  56931. };
  56932. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  56933. if (this._shadowMap2) {
  56934. this._shadowMap2.dispose();
  56935. this._shadowMap2 = null;
  56936. }
  56937. if (this._boxBlurPostprocess) {
  56938. this._boxBlurPostprocess.dispose();
  56939. this._boxBlurPostprocess = null;
  56940. }
  56941. if (this._kernelBlurXPostprocess) {
  56942. this._kernelBlurXPostprocess.dispose();
  56943. this._kernelBlurXPostprocess = null;
  56944. }
  56945. if (this._kernelBlurYPostprocess) {
  56946. this._kernelBlurYPostprocess.dispose();
  56947. this._kernelBlurYPostprocess = null;
  56948. }
  56949. this._blurPostProcesses = [];
  56950. };
  56951. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  56952. if (this._shadowMap) {
  56953. this._shadowMap.dispose();
  56954. this._shadowMap = null;
  56955. }
  56956. this._disposeBlurPostProcesses();
  56957. };
  56958. /**
  56959. * Disposes the ShadowGenerator.
  56960. * Returns nothing.
  56961. */
  56962. ShadowGenerator.prototype.dispose = function () {
  56963. this._disposeRTTandPostProcesses();
  56964. if (this._light) {
  56965. this._light._shadowGenerator = null;
  56966. this._light._markMeshesAsLightDirty();
  56967. }
  56968. };
  56969. /**
  56970. * Serializes the shadow generator setup to a json object.
  56971. * @returns The serialized JSON object
  56972. */
  56973. ShadowGenerator.prototype.serialize = function () {
  56974. var serializationObject = {};
  56975. var shadowMap = this.getShadowMap();
  56976. if (!shadowMap) {
  56977. return serializationObject;
  56978. }
  56979. serializationObject.lightId = this._light.id;
  56980. serializationObject.mapSize = shadowMap.getRenderSize();
  56981. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  56982. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  56983. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56984. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56985. serializationObject.usePoissonSampling = this.usePoissonSampling;
  56986. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  56987. serializationObject.depthScale = this.depthScale;
  56988. serializationObject.darkness = this.getDarkness();
  56989. serializationObject.blurBoxOffset = this.blurBoxOffset;
  56990. serializationObject.blurKernel = this.blurKernel;
  56991. serializationObject.blurScale = this.blurScale;
  56992. serializationObject.useKernelBlur = this.useKernelBlur;
  56993. serializationObject.transparencyShadow = this._transparencyShadow;
  56994. serializationObject.renderList = [];
  56995. if (shadowMap.renderList) {
  56996. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  56997. var mesh = shadowMap.renderList[meshIndex];
  56998. serializationObject.renderList.push(mesh.id);
  56999. }
  57000. }
  57001. return serializationObject;
  57002. };
  57003. /**
  57004. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  57005. * @param parsedShadowGenerator The JSON object to parse
  57006. * @param scene The scene to create the shadow map for
  57007. * @returns The parsed shadow generator
  57008. */
  57009. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  57010. //casting to point light, as light is missing the position attr and typescript complains.
  57011. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  57012. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  57013. var shadowMap = shadowGenerator.getShadowMap();
  57014. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  57015. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  57016. meshes.forEach(function (mesh) {
  57017. if (!shadowMap) {
  57018. return;
  57019. }
  57020. if (!shadowMap.renderList) {
  57021. shadowMap.renderList = [];
  57022. }
  57023. shadowMap.renderList.push(mesh);
  57024. });
  57025. }
  57026. if (parsedShadowGenerator.usePoissonSampling) {
  57027. shadowGenerator.usePoissonSampling = true;
  57028. }
  57029. else if (parsedShadowGenerator.useExponentialShadowMap) {
  57030. shadowGenerator.useExponentialShadowMap = true;
  57031. }
  57032. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  57033. shadowGenerator.useBlurExponentialShadowMap = true;
  57034. }
  57035. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  57036. shadowGenerator.useCloseExponentialShadowMap = true;
  57037. }
  57038. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  57039. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  57040. }
  57041. else if (parsedShadowGenerator.useVarianceShadowMap) {
  57042. shadowGenerator.useExponentialShadowMap = true;
  57043. }
  57044. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  57045. shadowGenerator.useBlurExponentialShadowMap = true;
  57046. }
  57047. if (parsedShadowGenerator.depthScale) {
  57048. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  57049. }
  57050. if (parsedShadowGenerator.blurScale) {
  57051. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  57052. }
  57053. if (parsedShadowGenerator.blurBoxOffset) {
  57054. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  57055. }
  57056. if (parsedShadowGenerator.useKernelBlur) {
  57057. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  57058. }
  57059. if (parsedShadowGenerator.blurKernel) {
  57060. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  57061. }
  57062. if (parsedShadowGenerator.bias !== undefined) {
  57063. shadowGenerator.bias = parsedShadowGenerator.bias;
  57064. }
  57065. if (parsedShadowGenerator.darkness) {
  57066. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  57067. }
  57068. if (parsedShadowGenerator.transparencyShadow) {
  57069. shadowGenerator.setTransparencyShadow(true);
  57070. }
  57071. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  57072. return shadowGenerator;
  57073. };
  57074. ShadowGenerator._FILTER_NONE = 0;
  57075. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  57076. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  57077. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  57078. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  57079. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  57080. return ShadowGenerator;
  57081. }());
  57082. BABYLON.ShadowGenerator = ShadowGenerator;
  57083. })(BABYLON || (BABYLON = {}));
  57084. //# sourceMappingURL=babylon.shadowGenerator.js.map
  57085. var BABYLON;
  57086. (function (BABYLON) {
  57087. var DefaultLoadingScreen = /** @class */ (function () {
  57088. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  57089. if (_loadingText === void 0) { _loadingText = ""; }
  57090. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  57091. var _this = this;
  57092. this._renderingCanvas = _renderingCanvas;
  57093. this._loadingText = _loadingText;
  57094. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  57095. // Resize
  57096. this._resizeLoadingUI = function () {
  57097. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  57098. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  57099. if (!_this._loadingDiv) {
  57100. return;
  57101. }
  57102. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  57103. _this._loadingDiv.style.left = canvasRect.left + "px";
  57104. _this._loadingDiv.style.top = canvasRect.top + "px";
  57105. _this._loadingDiv.style.width = canvasRect.width + "px";
  57106. _this._loadingDiv.style.height = canvasRect.height + "px";
  57107. };
  57108. }
  57109. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  57110. if (this._loadingDiv) {
  57111. // Do not add a loading screen if there is already one
  57112. return;
  57113. }
  57114. this._loadingDiv = document.createElement("div");
  57115. this._loadingDiv.id = "babylonjsLoadingDiv";
  57116. this._loadingDiv.style.opacity = "0";
  57117. this._loadingDiv.style.transition = "opacity 1.5s ease";
  57118. this._loadingDiv.style.pointerEvents = "none";
  57119. // Loading text
  57120. this._loadingTextDiv = document.createElement("div");
  57121. this._loadingTextDiv.style.position = "absolute";
  57122. this._loadingTextDiv.style.left = "0";
  57123. this._loadingTextDiv.style.top = "50%";
  57124. this._loadingTextDiv.style.marginTop = "80px";
  57125. this._loadingTextDiv.style.width = "100%";
  57126. this._loadingTextDiv.style.height = "20px";
  57127. this._loadingTextDiv.style.fontFamily = "Arial";
  57128. this._loadingTextDiv.style.fontSize = "14px";
  57129. this._loadingTextDiv.style.color = "white";
  57130. this._loadingTextDiv.style.textAlign = "center";
  57131. this._loadingTextDiv.innerHTML = "Loading";
  57132. this._loadingDiv.appendChild(this._loadingTextDiv);
  57133. //set the predefined text
  57134. this._loadingTextDiv.innerHTML = this._loadingText;
  57135. // Generating keyframes
  57136. var style = document.createElement('style');
  57137. style.type = 'text/css';
  57138. 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 }";
  57139. style.innerHTML = keyFrames;
  57140. document.getElementsByTagName('head')[0].appendChild(style);
  57141. // Loading img
  57142. var imgBack = new Image();
  57143. 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";
  57144. imgBack.style.position = "absolute";
  57145. imgBack.style.left = "50%";
  57146. imgBack.style.top = "50%";
  57147. imgBack.style.marginLeft = "-60px";
  57148. imgBack.style.marginTop = "-60px";
  57149. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  57150. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  57151. imgBack.style.transformOrigin = "50% 50%";
  57152. imgBack.style.webkitTransformOrigin = "50% 50%";
  57153. this._loadingDiv.appendChild(imgBack);
  57154. this._resizeLoadingUI();
  57155. window.addEventListener("resize", this._resizeLoadingUI);
  57156. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57157. document.body.appendChild(this._loadingDiv);
  57158. this._loadingDiv.style.opacity = "1";
  57159. };
  57160. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  57161. var _this = this;
  57162. if (!this._loadingDiv) {
  57163. return;
  57164. }
  57165. var onTransitionEnd = function () {
  57166. if (!_this._loadingDiv) {
  57167. return;
  57168. }
  57169. document.body.removeChild(_this._loadingDiv);
  57170. window.removeEventListener("resize", _this._resizeLoadingUI);
  57171. _this._loadingDiv = null;
  57172. };
  57173. this._loadingDiv.style.opacity = "0";
  57174. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  57175. };
  57176. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  57177. set: function (text) {
  57178. this._loadingText = text;
  57179. if (this._loadingTextDiv) {
  57180. this._loadingTextDiv.innerHTML = this._loadingText;
  57181. }
  57182. },
  57183. enumerable: true,
  57184. configurable: true
  57185. });
  57186. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  57187. get: function () {
  57188. return this._loadingDivBackgroundColor;
  57189. },
  57190. set: function (color) {
  57191. this._loadingDivBackgroundColor = color;
  57192. if (!this._loadingDiv) {
  57193. return;
  57194. }
  57195. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57196. },
  57197. enumerable: true,
  57198. configurable: true
  57199. });
  57200. return DefaultLoadingScreen;
  57201. }());
  57202. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  57203. })(BABYLON || (BABYLON = {}));
  57204. //# sourceMappingURL=babylon.loadingScreen.js.map
  57205. var BABYLON;
  57206. (function (BABYLON) {
  57207. var SceneLoaderProgressEvent = /** @class */ (function () {
  57208. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  57209. this.lengthComputable = lengthComputable;
  57210. this.loaded = loaded;
  57211. this.total = total;
  57212. }
  57213. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  57214. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  57215. };
  57216. return SceneLoaderProgressEvent;
  57217. }());
  57218. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  57219. var SceneLoader = /** @class */ (function () {
  57220. function SceneLoader() {
  57221. }
  57222. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  57223. get: function () {
  57224. return 0;
  57225. },
  57226. enumerable: true,
  57227. configurable: true
  57228. });
  57229. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  57230. get: function () {
  57231. return 1;
  57232. },
  57233. enumerable: true,
  57234. configurable: true
  57235. });
  57236. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  57237. get: function () {
  57238. return 2;
  57239. },
  57240. enumerable: true,
  57241. configurable: true
  57242. });
  57243. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  57244. get: function () {
  57245. return 3;
  57246. },
  57247. enumerable: true,
  57248. configurable: true
  57249. });
  57250. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  57251. get: function () {
  57252. return SceneLoader._ForceFullSceneLoadingForIncremental;
  57253. },
  57254. set: function (value) {
  57255. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  57256. },
  57257. enumerable: true,
  57258. configurable: true
  57259. });
  57260. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  57261. get: function () {
  57262. return SceneLoader._ShowLoadingScreen;
  57263. },
  57264. set: function (value) {
  57265. SceneLoader._ShowLoadingScreen = value;
  57266. },
  57267. enumerable: true,
  57268. configurable: true
  57269. });
  57270. Object.defineProperty(SceneLoader, "loggingLevel", {
  57271. get: function () {
  57272. return SceneLoader._loggingLevel;
  57273. },
  57274. set: function (value) {
  57275. SceneLoader._loggingLevel = value;
  57276. },
  57277. enumerable: true,
  57278. configurable: true
  57279. });
  57280. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  57281. get: function () {
  57282. return SceneLoader._CleanBoneMatrixWeights;
  57283. },
  57284. set: function (value) {
  57285. SceneLoader._CleanBoneMatrixWeights = value;
  57286. },
  57287. enumerable: true,
  57288. configurable: true
  57289. });
  57290. SceneLoader._getDefaultPlugin = function () {
  57291. return SceneLoader._registeredPlugins[".babylon"];
  57292. };
  57293. SceneLoader._getPluginForExtension = function (extension) {
  57294. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  57295. if (registeredPlugin) {
  57296. return registeredPlugin;
  57297. }
  57298. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  57299. return SceneLoader._getDefaultPlugin();
  57300. };
  57301. SceneLoader._getPluginForDirectLoad = function (data) {
  57302. for (var extension in SceneLoader._registeredPlugins) {
  57303. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  57304. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  57305. return SceneLoader._registeredPlugins[extension];
  57306. }
  57307. }
  57308. return SceneLoader._getDefaultPlugin();
  57309. };
  57310. SceneLoader._getPluginForFilename = function (sceneFilename) {
  57311. if (sceneFilename.name) {
  57312. sceneFilename = sceneFilename.name;
  57313. }
  57314. var queryStringPosition = sceneFilename.indexOf("?");
  57315. if (queryStringPosition !== -1) {
  57316. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  57317. }
  57318. var dotPosition = sceneFilename.lastIndexOf(".");
  57319. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  57320. return SceneLoader._getPluginForExtension(extension);
  57321. };
  57322. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  57323. SceneLoader._getDirectLoad = function (sceneFilename) {
  57324. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  57325. return sceneFilename.substr(5);
  57326. }
  57327. return null;
  57328. };
  57329. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  57330. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  57331. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  57332. var plugin;
  57333. if (registeredPlugin.plugin.createPlugin) {
  57334. plugin = registeredPlugin.plugin.createPlugin();
  57335. }
  57336. else {
  57337. plugin = registeredPlugin.plugin;
  57338. }
  57339. var useArrayBuffer = registeredPlugin.isBinary;
  57340. var database;
  57341. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  57342. var dataCallback = function (data, responseURL) {
  57343. if (scene.isDisposed) {
  57344. onError("Scene has been disposed");
  57345. return;
  57346. }
  57347. scene.database = database;
  57348. onSuccess(plugin, data, responseURL);
  57349. };
  57350. var request = null;
  57351. var pluginDisposed = false;
  57352. var onDisposeObservable = plugin.onDisposeObservable;
  57353. if (onDisposeObservable) {
  57354. onDisposeObservable.add(function () {
  57355. pluginDisposed = true;
  57356. if (request) {
  57357. request.abort();
  57358. request = null;
  57359. }
  57360. onDispose();
  57361. });
  57362. }
  57363. var manifestChecked = function () {
  57364. if (pluginDisposed) {
  57365. return;
  57366. }
  57367. var url = rootUrl + sceneFilename;
  57368. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  57369. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  57370. } : undefined, database, useArrayBuffer, function (request, exception) {
  57371. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  57372. });
  57373. };
  57374. if (directLoad) {
  57375. dataCallback(directLoad);
  57376. return plugin;
  57377. }
  57378. if (rootUrl.indexOf("file:") === -1) {
  57379. if (scene.getEngine().enableOfflineSupport) {
  57380. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  57381. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  57382. }
  57383. else {
  57384. manifestChecked();
  57385. }
  57386. }
  57387. else {
  57388. var fileOrString = sceneFilename;
  57389. if (fileOrString.name) {
  57390. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  57391. }
  57392. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  57393. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  57394. }
  57395. else {
  57396. onError("Unable to find file named " + sceneFilename);
  57397. }
  57398. }
  57399. return plugin;
  57400. };
  57401. // Public functions
  57402. SceneLoader.GetPluginForExtension = function (extension) {
  57403. return SceneLoader._getPluginForExtension(extension).plugin;
  57404. };
  57405. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  57406. return !!SceneLoader._registeredPlugins[extension];
  57407. };
  57408. SceneLoader.RegisterPlugin = function (plugin) {
  57409. if (typeof plugin.extensions === "string") {
  57410. var extension = plugin.extensions;
  57411. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57412. plugin: plugin,
  57413. isBinary: false
  57414. };
  57415. }
  57416. else {
  57417. var extensions = plugin.extensions;
  57418. Object.keys(extensions).forEach(function (extension) {
  57419. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57420. plugin: plugin,
  57421. isBinary: extensions[extension].isBinary
  57422. };
  57423. });
  57424. }
  57425. };
  57426. /**
  57427. * Import meshes into a scene
  57428. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  57429. * @param rootUrl a string that defines the root url for scene and resources
  57430. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57431. * @param scene the instance of BABYLON.Scene to append to
  57432. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  57433. * @param onProgress a callback with a progress event for each file being loaded
  57434. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57435. */
  57436. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57437. var _this = this;
  57438. if (onSuccess === void 0) { onSuccess = null; }
  57439. if (onProgress === void 0) { onProgress = null; }
  57440. if (onError === void 0) { onError = null; }
  57441. if (pluginExtension === void 0) { pluginExtension = null; }
  57442. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57443. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57444. return null;
  57445. }
  57446. var loadingToken = {};
  57447. scene._addPendingData(loadingToken);
  57448. var disposeHandler = function () {
  57449. scene._removePendingData(loadingToken);
  57450. };
  57451. var errorHandler = function (message, exception) {
  57452. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  57453. if (onError) {
  57454. onError(scene, errorMessage, exception);
  57455. }
  57456. else {
  57457. BABYLON.Tools.Error(errorMessage);
  57458. // should the exception be thrown?
  57459. }
  57460. disposeHandler();
  57461. };
  57462. var progressHandler = onProgress ? function (event) {
  57463. try {
  57464. onProgress(event);
  57465. }
  57466. catch (e) {
  57467. errorHandler("Error in onProgress callback", e);
  57468. }
  57469. } : undefined;
  57470. var successHandler = function (meshes, particleSystems, skeletons) {
  57471. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  57472. if (onSuccess) {
  57473. try {
  57474. onSuccess(meshes, particleSystems, skeletons);
  57475. }
  57476. catch (e) {
  57477. errorHandler("Error in onSuccess callback", e);
  57478. }
  57479. }
  57480. scene._removePendingData(loadingToken);
  57481. };
  57482. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57483. if (plugin.rewriteRootURL) {
  57484. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  57485. }
  57486. if (sceneFilename === "") {
  57487. if (sceneFilename === "") {
  57488. rootUrl = _this._StripFilenameFromRootUrl(rootUrl);
  57489. }
  57490. }
  57491. if (plugin.importMesh) {
  57492. var syncedPlugin = plugin;
  57493. var meshes = new Array();
  57494. var particleSystems = new Array();
  57495. var skeletons = new Array();
  57496. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  57497. return;
  57498. }
  57499. scene.loadingPluginName = plugin.name;
  57500. successHandler(meshes, particleSystems, skeletons);
  57501. }
  57502. else {
  57503. var asyncedPlugin = plugin;
  57504. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  57505. scene.loadingPluginName = plugin.name;
  57506. successHandler(meshes, particleSystems, skeletons);
  57507. }, progressHandler, errorHandler);
  57508. }
  57509. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57510. };
  57511. /**
  57512. * Load a scene
  57513. * @param rootUrl a string that defines the root url for scene and resources
  57514. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57515. * @param engine is the instance of BABYLON.Engine to use to create the scene
  57516. * @param onSuccess a callback with the scene when import succeeds
  57517. * @param onProgress a callback with a progress event for each file being loaded
  57518. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57519. */
  57520. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  57521. if (onSuccess === void 0) { onSuccess = null; }
  57522. if (onProgress === void 0) { onProgress = null; }
  57523. if (onError === void 0) { onError = null; }
  57524. if (pluginExtension === void 0) { pluginExtension = null; }
  57525. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  57526. };
  57527. /**
  57528. * Append a scene
  57529. * @param rootUrl a string that defines the root url for scene and resources
  57530. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57531. * @param scene is the instance of BABYLON.Scene to append to
  57532. * @param onSuccess a callback with the scene when import succeeds
  57533. * @param onProgress a callback with a progress event for each file being loaded
  57534. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57535. */
  57536. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57537. var _this = this;
  57538. if (onSuccess === void 0) { onSuccess = null; }
  57539. if (onProgress === void 0) { onProgress = null; }
  57540. if (onError === void 0) { onError = null; }
  57541. if (pluginExtension === void 0) { pluginExtension = null; }
  57542. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57543. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57544. return null;
  57545. }
  57546. if (SceneLoader.ShowLoadingScreen) {
  57547. scene.getEngine().displayLoadingUI();
  57548. }
  57549. var loadingToken = {};
  57550. scene._addPendingData(loadingToken);
  57551. var disposeHandler = function () {
  57552. scene._removePendingData(loadingToken);
  57553. scene.getEngine().hideLoadingUI();
  57554. };
  57555. var errorHandler = function (message, exception) {
  57556. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57557. if (onError) {
  57558. onError(scene, errorMessage, exception);
  57559. }
  57560. else {
  57561. BABYLON.Tools.Error(errorMessage);
  57562. // should the exception be thrown?
  57563. }
  57564. disposeHandler();
  57565. };
  57566. var progressHandler = onProgress ? function (event) {
  57567. try {
  57568. onProgress(event);
  57569. }
  57570. catch (e) {
  57571. errorHandler("Error in onProgress callback", e);
  57572. }
  57573. } : undefined;
  57574. var successHandler = function () {
  57575. if (onSuccess) {
  57576. try {
  57577. onSuccess(scene);
  57578. }
  57579. catch (e) {
  57580. errorHandler("Error in onSuccess callback", e);
  57581. }
  57582. }
  57583. scene._removePendingData(loadingToken);
  57584. };
  57585. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57586. if (sceneFilename === "") {
  57587. rootUrl = _this._StripFilenameFromRootUrl(rootUrl);
  57588. }
  57589. if (plugin.load) {
  57590. var syncedPlugin = plugin;
  57591. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  57592. return;
  57593. }
  57594. scene.loadingPluginName = plugin.name;
  57595. successHandler();
  57596. }
  57597. else {
  57598. var asyncedPlugin = plugin;
  57599. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  57600. scene.loadingPluginName = plugin.name;
  57601. successHandler();
  57602. }, progressHandler, errorHandler);
  57603. }
  57604. if (SceneLoader.ShowLoadingScreen) {
  57605. scene.executeWhenReady(function () {
  57606. scene.getEngine().hideLoadingUI();
  57607. });
  57608. }
  57609. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57610. };
  57611. SceneLoader._StripFilenameFromRootUrl = function (rootUrl) {
  57612. // We need to strip the filename off from the rootUrl
  57613. var lastSlash = rootUrl.lastIndexOf("/");
  57614. if (lastSlash > -1) {
  57615. rootUrl = rootUrl.substr(0, lastSlash + 1);
  57616. }
  57617. return rootUrl;
  57618. };
  57619. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57620. if (onSuccess === void 0) { onSuccess = null; }
  57621. if (onProgress === void 0) { onProgress = null; }
  57622. if (onError === void 0) { onError = null; }
  57623. if (pluginExtension === void 0) { pluginExtension = null; }
  57624. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57625. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57626. return null;
  57627. }
  57628. var loadingToken = {};
  57629. scene._addPendingData(loadingToken);
  57630. var disposeHandler = function () {
  57631. scene._removePendingData(loadingToken);
  57632. };
  57633. var errorHandler = function (message, exception) {
  57634. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57635. if (onError) {
  57636. onError(scene, errorMessage, exception);
  57637. }
  57638. else {
  57639. BABYLON.Tools.Error(errorMessage);
  57640. // should the exception be thrown?
  57641. }
  57642. disposeHandler();
  57643. };
  57644. var progressHandler = onProgress ? function (event) {
  57645. try {
  57646. onProgress(event);
  57647. }
  57648. catch (e) {
  57649. errorHandler("Error in onProgress callback", e);
  57650. }
  57651. } : undefined;
  57652. var successHandler = function (assets) {
  57653. if (onSuccess) {
  57654. try {
  57655. onSuccess(assets);
  57656. }
  57657. catch (e) {
  57658. errorHandler("Error in onSuccess callback", e);
  57659. }
  57660. }
  57661. scene._removePendingData(loadingToken);
  57662. };
  57663. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57664. if (plugin.loadAssets) {
  57665. var syncedPlugin = plugin;
  57666. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  57667. if (!assetContainer) {
  57668. return;
  57669. }
  57670. scene.loadingPluginName = plugin.name;
  57671. successHandler(assetContainer);
  57672. }
  57673. else if (plugin.loadAssetsAsync) {
  57674. var asyncedPlugin = plugin;
  57675. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  57676. if (assetContainer) {
  57677. scene.loadingPluginName = plugin.name;
  57678. successHandler(assetContainer);
  57679. }
  57680. }, progressHandler, errorHandler);
  57681. }
  57682. else {
  57683. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  57684. }
  57685. if (SceneLoader.ShowLoadingScreen) {
  57686. scene.executeWhenReady(function () {
  57687. scene.getEngine().hideLoadingUI();
  57688. });
  57689. }
  57690. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57691. };
  57692. // Flags
  57693. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  57694. SceneLoader._ShowLoadingScreen = true;
  57695. SceneLoader._CleanBoneMatrixWeights = false;
  57696. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  57697. // Members
  57698. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  57699. SceneLoader._registeredPlugins = {};
  57700. return SceneLoader;
  57701. }());
  57702. BABYLON.SceneLoader = SceneLoader;
  57703. ;
  57704. })(BABYLON || (BABYLON = {}));
  57705. //# sourceMappingURL=babylon.sceneLoader.js.map
  57706. var BABYLON;
  57707. (function (BABYLON) {
  57708. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  57709. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57710. var parsedMaterial = parsedData.materials[index];
  57711. if (parsedMaterial.id === id) {
  57712. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57713. }
  57714. }
  57715. return null;
  57716. };
  57717. var isDescendantOf = function (mesh, names, hierarchyIds) {
  57718. for (var i in names) {
  57719. if (mesh.name === names[i]) {
  57720. hierarchyIds.push(mesh.id);
  57721. return true;
  57722. }
  57723. }
  57724. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  57725. hierarchyIds.push(mesh.id);
  57726. return true;
  57727. }
  57728. return false;
  57729. };
  57730. var logOperation = function (operation, producer) {
  57731. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  57732. };
  57733. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  57734. if (addToScene === void 0) { addToScene = false; }
  57735. var container = new BABYLON.AssetContainer(scene);
  57736. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57737. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57738. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57739. // and avoid problems with multiple concurrent .babylon loads.
  57740. var log = "importScene has failed JSON parse";
  57741. try {
  57742. var parsedData = JSON.parse(data);
  57743. log = "";
  57744. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57745. var index;
  57746. var cache;
  57747. // Lights
  57748. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  57749. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  57750. var parsedLight = parsedData.lights[index];
  57751. var light = BABYLON.Light.Parse(parsedLight, scene);
  57752. if (light) {
  57753. container.lights.push(light);
  57754. log += (index === 0 ? "\n\tLights:" : "");
  57755. log += "\n\t\t" + light.toString(fullDetails);
  57756. }
  57757. }
  57758. }
  57759. // Animations
  57760. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  57761. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  57762. var parsedAnimation = parsedData.animations[index];
  57763. var animation = BABYLON.Animation.Parse(parsedAnimation);
  57764. scene.animations.push(animation);
  57765. container.animations.push(animation);
  57766. log += (index === 0 ? "\n\tAnimations:" : "");
  57767. log += "\n\t\t" + animation.toString(fullDetails);
  57768. }
  57769. }
  57770. // Materials
  57771. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  57772. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57773. var parsedMaterial = parsedData.materials[index];
  57774. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57775. container.materials.push(mat);
  57776. log += (index === 0 ? "\n\tMaterials:" : "");
  57777. log += "\n\t\t" + mat.toString(fullDetails);
  57778. }
  57779. }
  57780. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57781. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  57782. var parsedMultiMaterial = parsedData.multiMaterials[index];
  57783. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57784. container.multiMaterials.push(mmat);
  57785. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  57786. log += "\n\t\t" + mmat.toString(fullDetails);
  57787. }
  57788. }
  57789. // Morph targets
  57790. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  57791. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  57792. var managerData = _a[_i];
  57793. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  57794. }
  57795. }
  57796. // Skeletons
  57797. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57798. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  57799. var parsedSkeleton = parsedData.skeletons[index];
  57800. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57801. container.skeletons.push(skeleton);
  57802. log += (index === 0 ? "\n\tSkeletons:" : "");
  57803. log += "\n\t\t" + skeleton.toString(fullDetails);
  57804. }
  57805. }
  57806. // Geometries
  57807. var geometries = parsedData.geometries;
  57808. if (geometries !== undefined && geometries !== null) {
  57809. var addedGeometry = new Array();
  57810. // Boxes
  57811. var boxes = geometries.boxes;
  57812. if (boxes !== undefined && boxes !== null) {
  57813. for (index = 0, cache = boxes.length; index < cache; index++) {
  57814. var parsedBox = boxes[index];
  57815. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  57816. }
  57817. }
  57818. // Spheres
  57819. var spheres = geometries.spheres;
  57820. if (spheres !== undefined && spheres !== null) {
  57821. for (index = 0, cache = spheres.length; index < cache; index++) {
  57822. var parsedSphere = spheres[index];
  57823. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  57824. }
  57825. }
  57826. // Cylinders
  57827. var cylinders = geometries.cylinders;
  57828. if (cylinders !== undefined && cylinders !== null) {
  57829. for (index = 0, cache = cylinders.length; index < cache; index++) {
  57830. var parsedCylinder = cylinders[index];
  57831. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  57832. }
  57833. }
  57834. // Toruses
  57835. var toruses = geometries.toruses;
  57836. if (toruses !== undefined && toruses !== null) {
  57837. for (index = 0, cache = toruses.length; index < cache; index++) {
  57838. var parsedTorus = toruses[index];
  57839. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  57840. }
  57841. }
  57842. // Grounds
  57843. var grounds = geometries.grounds;
  57844. if (grounds !== undefined && grounds !== null) {
  57845. for (index = 0, cache = grounds.length; index < cache; index++) {
  57846. var parsedGround = grounds[index];
  57847. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  57848. }
  57849. }
  57850. // Planes
  57851. var planes = geometries.planes;
  57852. if (planes !== undefined && planes !== null) {
  57853. for (index = 0, cache = planes.length; index < cache; index++) {
  57854. var parsedPlane = planes[index];
  57855. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  57856. }
  57857. }
  57858. // TorusKnots
  57859. var torusKnots = geometries.torusKnots;
  57860. if (torusKnots !== undefined && torusKnots !== null) {
  57861. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  57862. var parsedTorusKnot = torusKnots[index];
  57863. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  57864. }
  57865. }
  57866. // VertexData
  57867. var vertexData = geometries.vertexData;
  57868. if (vertexData !== undefined && vertexData !== null) {
  57869. for (index = 0, cache = vertexData.length; index < cache; index++) {
  57870. var parsedVertexData = vertexData[index];
  57871. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  57872. }
  57873. }
  57874. addedGeometry.forEach(function (g) {
  57875. if (g) {
  57876. container.geometries.push(g);
  57877. }
  57878. });
  57879. }
  57880. // Transform nodes
  57881. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  57882. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  57883. var parsedTransformNode = parsedData.transformNodes[index];
  57884. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  57885. container.transformNodes.push(node);
  57886. }
  57887. }
  57888. // Meshes
  57889. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57890. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57891. var parsedMesh = parsedData.meshes[index];
  57892. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57893. container.meshes.push(mesh);
  57894. log += (index === 0 ? "\n\tMeshes:" : "");
  57895. log += "\n\t\t" + mesh.toString(fullDetails);
  57896. }
  57897. }
  57898. // Cameras
  57899. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  57900. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  57901. var parsedCamera = parsedData.cameras[index];
  57902. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  57903. container.cameras.push(camera);
  57904. log += (index === 0 ? "\n\tCameras:" : "");
  57905. log += "\n\t\t" + camera.toString(fullDetails);
  57906. }
  57907. }
  57908. // Browsing all the graph to connect the dots
  57909. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  57910. var camera = scene.cameras[index];
  57911. if (camera._waitingParentId) {
  57912. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  57913. camera._waitingParentId = null;
  57914. }
  57915. }
  57916. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57917. var light_1 = scene.lights[index];
  57918. if (light_1 && light_1._waitingParentId) {
  57919. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  57920. light_1._waitingParentId = null;
  57921. }
  57922. }
  57923. // Sounds
  57924. // TODO: add sound
  57925. var loadedSounds = [];
  57926. var loadedSound;
  57927. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  57928. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  57929. var parsedSound = parsedData.sounds[index];
  57930. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57931. if (!parsedSound.url)
  57932. parsedSound.url = parsedSound.name;
  57933. if (!loadedSounds[parsedSound.url]) {
  57934. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  57935. loadedSounds[parsedSound.url] = loadedSound;
  57936. container.sounds.push(loadedSound);
  57937. }
  57938. else {
  57939. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  57940. }
  57941. }
  57942. else {
  57943. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  57944. }
  57945. }
  57946. }
  57947. loadedSounds = [];
  57948. // Connect parents & children and parse actions
  57949. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  57950. var transformNode = scene.transformNodes[index];
  57951. if (transformNode._waitingParentId) {
  57952. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  57953. transformNode._waitingParentId = null;
  57954. }
  57955. }
  57956. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57957. var mesh = scene.meshes[index];
  57958. if (mesh._waitingParentId) {
  57959. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  57960. mesh._waitingParentId = null;
  57961. }
  57962. if (mesh._waitingActions) {
  57963. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  57964. mesh._waitingActions = null;
  57965. }
  57966. }
  57967. // freeze world matrix application
  57968. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57969. var currentMesh = scene.meshes[index];
  57970. if (currentMesh._waitingFreezeWorldMatrix) {
  57971. currentMesh.freezeWorldMatrix();
  57972. currentMesh._waitingFreezeWorldMatrix = null;
  57973. }
  57974. else {
  57975. currentMesh.computeWorldMatrix(true);
  57976. }
  57977. }
  57978. // Particles Systems
  57979. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57980. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57981. var parsedParticleSystem = parsedData.particleSystems[index];
  57982. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57983. container.particleSystems.push(ps);
  57984. }
  57985. }
  57986. // Lens flares
  57987. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  57988. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  57989. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  57990. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  57991. container.lensFlareSystems.push(lf);
  57992. }
  57993. }
  57994. // Shadows
  57995. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  57996. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  57997. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  57998. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  57999. container.shadowGenerators.push(sg);
  58000. }
  58001. }
  58002. // Lights exclusions / inclusions
  58003. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58004. var light_2 = scene.lights[index];
  58005. // Excluded check
  58006. if (light_2._excludedMeshesIds.length > 0) {
  58007. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  58008. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  58009. if (excludedMesh) {
  58010. light_2.excludedMeshes.push(excludedMesh);
  58011. }
  58012. }
  58013. light_2._excludedMeshesIds = [];
  58014. }
  58015. // Included check
  58016. if (light_2._includedOnlyMeshesIds.length > 0) {
  58017. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  58018. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  58019. if (includedOnlyMesh) {
  58020. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  58021. }
  58022. }
  58023. light_2._includedOnlyMeshesIds = [];
  58024. }
  58025. }
  58026. // Actions (scene)
  58027. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  58028. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  58029. }
  58030. if (!addToScene) {
  58031. container.removeAllFromScene();
  58032. }
  58033. return container;
  58034. }
  58035. catch (err) {
  58036. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  58037. if (onError) {
  58038. onError(msg, err);
  58039. }
  58040. else {
  58041. BABYLON.Tools.Log(msg);
  58042. throw err;
  58043. }
  58044. }
  58045. finally {
  58046. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58047. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58048. }
  58049. }
  58050. return null;
  58051. };
  58052. BABYLON.SceneLoader.RegisterPlugin({
  58053. name: "babylon.js",
  58054. extensions: ".babylon",
  58055. canDirectLoad: function (data) {
  58056. if (data.indexOf("babylon") !== -1) {
  58057. return true;
  58058. }
  58059. return false;
  58060. },
  58061. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  58062. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58063. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58064. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58065. // and avoid problems with multiple concurrent .babylon loads.
  58066. var log = "importMesh has failed JSON parse";
  58067. try {
  58068. var parsedData = JSON.parse(data);
  58069. log = "";
  58070. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58071. if (!meshesNames) {
  58072. meshesNames = null;
  58073. }
  58074. else if (!Array.isArray(meshesNames)) {
  58075. meshesNames = [meshesNames];
  58076. }
  58077. var hierarchyIds = new Array();
  58078. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58079. var loadedSkeletonsIds = [];
  58080. var loadedMaterialsIds = [];
  58081. var index;
  58082. var cache;
  58083. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58084. var parsedMesh = parsedData.meshes[index];
  58085. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  58086. if (meshesNames !== null) {
  58087. // Remove found mesh name from list.
  58088. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  58089. }
  58090. //Geometry?
  58091. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  58092. //does the file contain geometries?
  58093. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  58094. //find the correct geometry and add it to the scene
  58095. var found = false;
  58096. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  58097. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  58098. return;
  58099. }
  58100. else {
  58101. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  58102. if (parsedGeometryData.id === parsedMesh.geometryId) {
  58103. switch (geometryType) {
  58104. case "boxes":
  58105. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  58106. break;
  58107. case "spheres":
  58108. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  58109. break;
  58110. case "cylinders":
  58111. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  58112. break;
  58113. case "toruses":
  58114. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  58115. break;
  58116. case "grounds":
  58117. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  58118. break;
  58119. case "planes":
  58120. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  58121. break;
  58122. case "torusKnots":
  58123. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  58124. break;
  58125. case "vertexData":
  58126. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  58127. break;
  58128. }
  58129. found = true;
  58130. }
  58131. });
  58132. }
  58133. });
  58134. if (found === false) {
  58135. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  58136. }
  58137. }
  58138. }
  58139. // Material ?
  58140. if (parsedMesh.materialId) {
  58141. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  58142. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58143. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  58144. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  58145. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  58146. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  58147. var subMatId = parsedMultiMaterial.materials[matIndex];
  58148. loadedMaterialsIds.push(subMatId);
  58149. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  58150. log += "\n\tMaterial " + mat.toString(fullDetails);
  58151. }
  58152. loadedMaterialsIds.push(parsedMultiMaterial.id);
  58153. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58154. materialFound = true;
  58155. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  58156. break;
  58157. }
  58158. }
  58159. }
  58160. if (materialFound === false) {
  58161. loadedMaterialsIds.push(parsedMesh.materialId);
  58162. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  58163. if (!mat) {
  58164. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  58165. }
  58166. else {
  58167. log += "\n\tMaterial " + mat.toString(fullDetails);
  58168. }
  58169. }
  58170. }
  58171. // Skeleton ?
  58172. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58173. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  58174. if (skeletonAlreadyLoaded === false) {
  58175. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  58176. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  58177. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  58178. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58179. skeletons.push(skeleton);
  58180. loadedSkeletonsIds.push(parsedSkeleton.id);
  58181. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  58182. }
  58183. }
  58184. }
  58185. }
  58186. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58187. meshes.push(mesh);
  58188. log += "\n\tMesh " + mesh.toString(fullDetails);
  58189. }
  58190. }
  58191. // Connecting parents
  58192. var currentMesh;
  58193. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58194. currentMesh = scene.meshes[index];
  58195. if (currentMesh._waitingParentId) {
  58196. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  58197. currentMesh._waitingParentId = null;
  58198. }
  58199. }
  58200. // freeze and compute world matrix application
  58201. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58202. currentMesh = scene.meshes[index];
  58203. if (currentMesh._waitingFreezeWorldMatrix) {
  58204. currentMesh.freezeWorldMatrix();
  58205. currentMesh._waitingFreezeWorldMatrix = null;
  58206. }
  58207. else {
  58208. currentMesh.computeWorldMatrix(true);
  58209. }
  58210. }
  58211. }
  58212. // Particles
  58213. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58214. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58215. var parsedParticleSystem = parsedData.particleSystems[index];
  58216. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  58217. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  58218. }
  58219. }
  58220. }
  58221. return true;
  58222. }
  58223. catch (err) {
  58224. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  58225. if (onError) {
  58226. onError(msg, err);
  58227. }
  58228. else {
  58229. BABYLON.Tools.Log(msg);
  58230. throw err;
  58231. }
  58232. }
  58233. finally {
  58234. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58235. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58236. }
  58237. }
  58238. return false;
  58239. },
  58240. load: function (scene, data, rootUrl, onError) {
  58241. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58242. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58243. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58244. // and avoid problems with multiple concurrent .babylon loads.
  58245. var log = "importScene has failed JSON parse";
  58246. try {
  58247. var parsedData = JSON.parse(data);
  58248. log = "";
  58249. // Scene
  58250. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  58251. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  58252. }
  58253. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  58254. scene.autoClear = parsedData.autoClear;
  58255. }
  58256. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  58257. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  58258. }
  58259. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  58260. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  58261. }
  58262. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  58263. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  58264. }
  58265. // Fog
  58266. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  58267. scene.fogMode = parsedData.fogMode;
  58268. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  58269. scene.fogStart = parsedData.fogStart;
  58270. scene.fogEnd = parsedData.fogEnd;
  58271. scene.fogDensity = parsedData.fogDensity;
  58272. log += "\tFog mode for scene: ";
  58273. switch (scene.fogMode) {
  58274. // getters not compiling, so using hardcoded
  58275. case 1:
  58276. log += "exp\n";
  58277. break;
  58278. case 2:
  58279. log += "exp2\n";
  58280. break;
  58281. case 3:
  58282. log += "linear\n";
  58283. break;
  58284. }
  58285. }
  58286. //Physics
  58287. if (parsedData.physicsEnabled) {
  58288. var physicsPlugin;
  58289. if (parsedData.physicsEngine === "cannon") {
  58290. physicsPlugin = new BABYLON.CannonJSPlugin();
  58291. }
  58292. else if (parsedData.physicsEngine === "oimo") {
  58293. physicsPlugin = new BABYLON.OimoJSPlugin();
  58294. }
  58295. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  58296. //else - default engine, which is currently oimo
  58297. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  58298. scene.enablePhysics(physicsGravity, physicsPlugin);
  58299. }
  58300. // Metadata
  58301. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  58302. scene.metadata = parsedData.metadata;
  58303. }
  58304. //collisions, if defined. otherwise, default is true
  58305. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  58306. scene.collisionsEnabled = parsedData.collisionsEnabled;
  58307. }
  58308. scene.workerCollisions = !!parsedData.workerCollisions;
  58309. var container = loadAssets(scene, data, rootUrl, onerror, true);
  58310. if (!container) {
  58311. return false;
  58312. }
  58313. if (parsedData.autoAnimate) {
  58314. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  58315. }
  58316. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  58317. scene.setActiveCameraByID(parsedData.activeCameraID);
  58318. }
  58319. // Environment texture
  58320. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  58321. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  58322. if (parsedData.createDefaultSkybox === true) {
  58323. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  58324. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  58325. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  58326. }
  58327. }
  58328. // Finish
  58329. return true;
  58330. }
  58331. catch (err) {
  58332. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  58333. if (onError) {
  58334. onError(msg, err);
  58335. }
  58336. else {
  58337. BABYLON.Tools.Log(msg);
  58338. throw err;
  58339. }
  58340. }
  58341. finally {
  58342. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58343. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58344. }
  58345. }
  58346. return false;
  58347. },
  58348. loadAssets: function (scene, data, rootUrl, onError) {
  58349. var container = loadAssets(scene, data, rootUrl, onerror);
  58350. return container;
  58351. }
  58352. });
  58353. })(BABYLON || (BABYLON = {}));
  58354. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  58355. var BABYLON;
  58356. (function (BABYLON) {
  58357. var FilesInput = /** @class */ (function () {
  58358. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  58359. this.onProcessFileCallback = function () { return true; };
  58360. this._engine = engine;
  58361. this._currentScene = scene;
  58362. this._sceneLoadedCallback = sceneLoadedCallback;
  58363. this._progressCallback = progressCallback;
  58364. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58365. this._textureLoadingCallback = textureLoadingCallback;
  58366. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  58367. this._onReloadCallback = onReloadCallback;
  58368. this._errorCallback = errorCallback;
  58369. }
  58370. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  58371. var _this = this;
  58372. if (elementToMonitor) {
  58373. this._elementToMonitor = elementToMonitor;
  58374. this._dragEnterHandler = function (e) { _this.drag(e); };
  58375. this._dragOverHandler = function (e) { _this.drag(e); };
  58376. this._dropHandler = function (e) { _this.drop(e); };
  58377. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  58378. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  58379. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  58380. }
  58381. };
  58382. FilesInput.prototype.dispose = function () {
  58383. if (!this._elementToMonitor) {
  58384. return;
  58385. }
  58386. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  58387. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  58388. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  58389. };
  58390. FilesInput.prototype.renderFunction = function () {
  58391. if (this._additionalRenderLoopLogicCallback) {
  58392. this._additionalRenderLoopLogicCallback();
  58393. }
  58394. if (this._currentScene) {
  58395. if (this._textureLoadingCallback) {
  58396. var remaining = this._currentScene.getWaitingItemsCount();
  58397. if (remaining > 0) {
  58398. this._textureLoadingCallback(remaining);
  58399. }
  58400. }
  58401. this._currentScene.render();
  58402. }
  58403. };
  58404. FilesInput.prototype.drag = function (e) {
  58405. e.stopPropagation();
  58406. e.preventDefault();
  58407. };
  58408. FilesInput.prototype.drop = function (eventDrop) {
  58409. eventDrop.stopPropagation();
  58410. eventDrop.preventDefault();
  58411. this.loadFiles(eventDrop);
  58412. };
  58413. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  58414. var _this = this;
  58415. var reader = folder.createReader();
  58416. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  58417. reader.readEntries(function (entries) {
  58418. remaining.count += entries.length;
  58419. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  58420. var entry = entries_1[_i];
  58421. if (entry.isFile) {
  58422. entry.file(function (file) {
  58423. file.correctName = relativePath + file.name;
  58424. files.push(file);
  58425. if (--remaining.count === 0) {
  58426. callback();
  58427. }
  58428. });
  58429. }
  58430. else if (entry.isDirectory) {
  58431. _this._traverseFolder(entry, files, remaining, callback);
  58432. }
  58433. }
  58434. if (--remaining.count) {
  58435. callback();
  58436. }
  58437. });
  58438. };
  58439. FilesInput.prototype._processFiles = function (files) {
  58440. for (var i = 0; i < files.length; i++) {
  58441. var name = files[i].correctName.toLowerCase();
  58442. var extension = name.split('.').pop();
  58443. if (!this.onProcessFileCallback(files[i], name, extension)) {
  58444. continue;
  58445. }
  58446. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  58447. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  58448. this._sceneFileToLoad = files[i];
  58449. }
  58450. else {
  58451. FilesInput.FilesToLoad[name] = files[i];
  58452. }
  58453. }
  58454. };
  58455. FilesInput.prototype.loadFiles = function (event) {
  58456. var _this = this;
  58457. if (this._startingProcessingFilesCallback)
  58458. this._startingProcessingFilesCallback();
  58459. // Handling data transfer via drag'n'drop
  58460. if (event && event.dataTransfer && event.dataTransfer.files) {
  58461. this._filesToLoad = event.dataTransfer.files;
  58462. }
  58463. // Handling files from input files
  58464. if (event && event.target && event.target.files) {
  58465. this._filesToLoad = event.target.files;
  58466. }
  58467. if (this._filesToLoad && this._filesToLoad.length > 0) {
  58468. var files_1 = new Array();
  58469. var folders = [];
  58470. var items = event.dataTransfer ? event.dataTransfer.items : null;
  58471. for (var i = 0; i < this._filesToLoad.length; i++) {
  58472. var fileToLoad = this._filesToLoad[i];
  58473. var name_1 = fileToLoad.name.toLowerCase();
  58474. var entry = void 0;
  58475. fileToLoad.correctName = name_1;
  58476. if (items) {
  58477. var item = items[i];
  58478. if (item.getAsEntry) {
  58479. entry = item.getAsEntry();
  58480. }
  58481. else if (item.webkitGetAsEntry) {
  58482. entry = item.webkitGetAsEntry();
  58483. }
  58484. }
  58485. if (!entry) {
  58486. files_1.push(fileToLoad);
  58487. }
  58488. else {
  58489. if (entry.isDirectory) {
  58490. folders.push(entry);
  58491. }
  58492. else {
  58493. files_1.push(fileToLoad);
  58494. }
  58495. }
  58496. }
  58497. if (folders.length === 0) {
  58498. this._processFiles(files_1);
  58499. this._processReload();
  58500. }
  58501. else {
  58502. var remaining = { count: folders.length };
  58503. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  58504. var folder = folders_1[_i];
  58505. this._traverseFolder(folder, files_1, remaining, function () {
  58506. _this._processFiles(files_1);
  58507. if (remaining.count === 0) {
  58508. _this._processReload();
  58509. }
  58510. });
  58511. }
  58512. }
  58513. }
  58514. };
  58515. FilesInput.prototype._processReload = function () {
  58516. if (this._onReloadCallback) {
  58517. this._onReloadCallback(this._sceneFileToLoad);
  58518. }
  58519. else {
  58520. this.reload();
  58521. }
  58522. };
  58523. FilesInput.prototype.reload = function () {
  58524. var _this = this;
  58525. // If a scene file has been provided
  58526. if (this._sceneFileToLoad) {
  58527. if (this._currentScene) {
  58528. if (BABYLON.Tools.errorsCount > 0) {
  58529. BABYLON.Tools.ClearLogCache();
  58530. }
  58531. this._engine.stopRenderLoop();
  58532. this._currentScene.dispose();
  58533. }
  58534. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  58535. _this._currentScene = newScene;
  58536. if (_this._sceneLoadedCallback) {
  58537. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  58538. }
  58539. // Wait for textures and shaders to be ready
  58540. _this._currentScene.executeWhenReady(function () {
  58541. _this._engine.runRenderLoop(function () {
  58542. _this.renderFunction();
  58543. });
  58544. });
  58545. }, function (progress) {
  58546. if (_this._progressCallback) {
  58547. _this._progressCallback(progress);
  58548. }
  58549. }, function (scene, message) {
  58550. _this._currentScene = scene;
  58551. if (_this._errorCallback) {
  58552. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  58553. }
  58554. });
  58555. }
  58556. else {
  58557. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  58558. }
  58559. };
  58560. FilesInput.FilesToLoad = {};
  58561. return FilesInput;
  58562. }());
  58563. BABYLON.FilesInput = FilesInput;
  58564. })(BABYLON || (BABYLON = {}));
  58565. //# sourceMappingURL=babylon.filesInput.js.map
  58566. var BABYLON;
  58567. (function (BABYLON) {
  58568. /**
  58569. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58570. * The underlying implementation relies on an associative array to ensure the best performances.
  58571. * The value can be anything including 'null' but except 'undefined'
  58572. */
  58573. var StringDictionary = /** @class */ (function () {
  58574. function StringDictionary() {
  58575. this._count = 0;
  58576. this._data = {};
  58577. }
  58578. /**
  58579. * This will clear this dictionary and copy the content from the 'source' one.
  58580. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58581. * @param source the dictionary to take the content from and copy to this dictionary
  58582. */
  58583. StringDictionary.prototype.copyFrom = function (source) {
  58584. var _this = this;
  58585. this.clear();
  58586. source.forEach(function (t, v) { return _this.add(t, v); });
  58587. };
  58588. /**
  58589. * Get a value based from its key
  58590. * @param key the given key to get the matching value from
  58591. * @return the value if found, otherwise undefined is returned
  58592. */
  58593. StringDictionary.prototype.get = function (key) {
  58594. var val = this._data[key];
  58595. if (val !== undefined) {
  58596. return val;
  58597. }
  58598. return undefined;
  58599. };
  58600. /**
  58601. * Get a value from its key or add it if it doesn't exist.
  58602. * This method will ensure you that a given key/data will be present in the dictionary.
  58603. * @param key the given key to get the matching value from
  58604. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58605. * The factory will only be invoked if there's no data for the given key.
  58606. * @return the value corresponding to the key.
  58607. */
  58608. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58609. var val = this.get(key);
  58610. if (val !== undefined) {
  58611. return val;
  58612. }
  58613. val = factory(key);
  58614. if (val) {
  58615. this.add(key, val);
  58616. }
  58617. return val;
  58618. };
  58619. /**
  58620. * Get a value from its key if present in the dictionary otherwise add it
  58621. * @param key the key to get the value from
  58622. * @param val if there's no such key/value pair in the dictionary add it with this value
  58623. * @return the value corresponding to the key
  58624. */
  58625. StringDictionary.prototype.getOrAdd = function (key, val) {
  58626. var curVal = this.get(key);
  58627. if (curVal !== undefined) {
  58628. return curVal;
  58629. }
  58630. this.add(key, val);
  58631. return val;
  58632. };
  58633. /**
  58634. * Check if there's a given key in the dictionary
  58635. * @param key the key to check for
  58636. * @return true if the key is present, false otherwise
  58637. */
  58638. StringDictionary.prototype.contains = function (key) {
  58639. return this._data[key] !== undefined;
  58640. };
  58641. /**
  58642. * Add a new key and its corresponding value
  58643. * @param key the key to add
  58644. * @param value the value corresponding to the key
  58645. * @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
  58646. */
  58647. StringDictionary.prototype.add = function (key, value) {
  58648. if (this._data[key] !== undefined) {
  58649. return false;
  58650. }
  58651. this._data[key] = value;
  58652. ++this._count;
  58653. return true;
  58654. };
  58655. StringDictionary.prototype.set = function (key, value) {
  58656. if (this._data[key] === undefined) {
  58657. return false;
  58658. }
  58659. this._data[key] = value;
  58660. return true;
  58661. };
  58662. /**
  58663. * Get the element of the given key and remove it from the dictionary
  58664. * @param key
  58665. */
  58666. StringDictionary.prototype.getAndRemove = function (key) {
  58667. var val = this.get(key);
  58668. if (val !== undefined) {
  58669. delete this._data[key];
  58670. --this._count;
  58671. return val;
  58672. }
  58673. return null;
  58674. };
  58675. /**
  58676. * Remove a key/value from the dictionary.
  58677. * @param key the key to remove
  58678. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58679. */
  58680. StringDictionary.prototype.remove = function (key) {
  58681. if (this.contains(key)) {
  58682. delete this._data[key];
  58683. --this._count;
  58684. return true;
  58685. }
  58686. return false;
  58687. };
  58688. /**
  58689. * Clear the whole content of the dictionary
  58690. */
  58691. StringDictionary.prototype.clear = function () {
  58692. this._data = {};
  58693. this._count = 0;
  58694. };
  58695. Object.defineProperty(StringDictionary.prototype, "count", {
  58696. get: function () {
  58697. return this._count;
  58698. },
  58699. enumerable: true,
  58700. configurable: true
  58701. });
  58702. /**
  58703. * Execute a callback on each key/val of the dictionary.
  58704. * Note that you can remove any element in this dictionary in the callback implementation
  58705. * @param callback the callback to execute on a given key/value pair
  58706. */
  58707. StringDictionary.prototype.forEach = function (callback) {
  58708. for (var cur in this._data) {
  58709. var val = this._data[cur];
  58710. callback(cur, val);
  58711. }
  58712. };
  58713. /**
  58714. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58715. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58716. * Note that you can remove any element in this dictionary in the callback implementation
  58717. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58718. */
  58719. StringDictionary.prototype.first = function (callback) {
  58720. for (var cur in this._data) {
  58721. var val = this._data[cur];
  58722. var res = callback(cur, val);
  58723. if (res) {
  58724. return res;
  58725. }
  58726. }
  58727. return null;
  58728. };
  58729. return StringDictionary;
  58730. }());
  58731. BABYLON.StringDictionary = StringDictionary;
  58732. })(BABYLON || (BABYLON = {}));
  58733. //# sourceMappingURL=babylon.stringDictionary.js.map
  58734. var BABYLON;
  58735. (function (BABYLON) {
  58736. var Tags = /** @class */ (function () {
  58737. function Tags() {
  58738. }
  58739. Tags.EnableFor = function (obj) {
  58740. obj._tags = obj._tags || {};
  58741. obj.hasTags = function () {
  58742. return Tags.HasTags(obj);
  58743. };
  58744. obj.addTags = function (tagsString) {
  58745. return Tags.AddTagsTo(obj, tagsString);
  58746. };
  58747. obj.removeTags = function (tagsString) {
  58748. return Tags.RemoveTagsFrom(obj, tagsString);
  58749. };
  58750. obj.matchesTagsQuery = function (tagsQuery) {
  58751. return Tags.MatchesQuery(obj, tagsQuery);
  58752. };
  58753. };
  58754. Tags.DisableFor = function (obj) {
  58755. delete obj._tags;
  58756. delete obj.hasTags;
  58757. delete obj.addTags;
  58758. delete obj.removeTags;
  58759. delete obj.matchesTagsQuery;
  58760. };
  58761. Tags.HasTags = function (obj) {
  58762. if (!obj._tags) {
  58763. return false;
  58764. }
  58765. return !BABYLON.Tools.IsEmpty(obj._tags);
  58766. };
  58767. Tags.GetTags = function (obj, asString) {
  58768. if (asString === void 0) { asString = true; }
  58769. if (!obj._tags) {
  58770. return null;
  58771. }
  58772. if (asString) {
  58773. var tagsArray = [];
  58774. for (var tag in obj._tags) {
  58775. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  58776. tagsArray.push(tag);
  58777. }
  58778. }
  58779. return tagsArray.join(" ");
  58780. }
  58781. else {
  58782. return obj._tags;
  58783. }
  58784. };
  58785. // the tags 'true' and 'false' are reserved and cannot be used as tags
  58786. // a tag cannot start with '||', '&&', and '!'
  58787. // it cannot contain whitespaces
  58788. Tags.AddTagsTo = function (obj, tagsString) {
  58789. if (!tagsString) {
  58790. return;
  58791. }
  58792. if (typeof tagsString !== "string") {
  58793. return;
  58794. }
  58795. var tags = tagsString.split(" ");
  58796. tags.forEach(function (tag, index, array) {
  58797. Tags._AddTagTo(obj, tag);
  58798. });
  58799. };
  58800. Tags._AddTagTo = function (obj, tag) {
  58801. tag = tag.trim();
  58802. if (tag === "" || tag === "true" || tag === "false") {
  58803. return;
  58804. }
  58805. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  58806. return;
  58807. }
  58808. Tags.EnableFor(obj);
  58809. obj._tags[tag] = true;
  58810. };
  58811. Tags.RemoveTagsFrom = function (obj, tagsString) {
  58812. if (!Tags.HasTags(obj)) {
  58813. return;
  58814. }
  58815. var tags = tagsString.split(" ");
  58816. for (var t in tags) {
  58817. Tags._RemoveTagFrom(obj, tags[t]);
  58818. }
  58819. };
  58820. Tags._RemoveTagFrom = function (obj, tag) {
  58821. delete obj._tags[tag];
  58822. };
  58823. Tags.MatchesQuery = function (obj, tagsQuery) {
  58824. if (tagsQuery === undefined) {
  58825. return true;
  58826. }
  58827. if (tagsQuery === "") {
  58828. return Tags.HasTags(obj);
  58829. }
  58830. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  58831. };
  58832. return Tags;
  58833. }());
  58834. BABYLON.Tags = Tags;
  58835. })(BABYLON || (BABYLON = {}));
  58836. //# sourceMappingURL=babylon.tags.js.map
  58837. var BABYLON;
  58838. (function (BABYLON) {
  58839. var AndOrNotEvaluator = /** @class */ (function () {
  58840. function AndOrNotEvaluator() {
  58841. }
  58842. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  58843. if (!query.match(/\([^\(\)]*\)/g)) {
  58844. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  58845. }
  58846. else {
  58847. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  58848. // remove parenthesis
  58849. r = r.slice(1, r.length - 1);
  58850. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  58851. });
  58852. }
  58853. if (query === "true") {
  58854. return true;
  58855. }
  58856. if (query === "false") {
  58857. return false;
  58858. }
  58859. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  58860. };
  58861. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  58862. evaluateCallback = evaluateCallback || (function (r) {
  58863. return r === "true" ? true : false;
  58864. });
  58865. var result;
  58866. var or = parenthesisContent.split("||");
  58867. for (var i in or) {
  58868. if (or.hasOwnProperty(i)) {
  58869. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  58870. var and = ori.split("&&");
  58871. if (and.length > 1) {
  58872. for (var j = 0; j < and.length; ++j) {
  58873. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  58874. if (andj !== "true" && andj !== "false") {
  58875. if (andj[0] === "!") {
  58876. result = !evaluateCallback(andj.substring(1));
  58877. }
  58878. else {
  58879. result = evaluateCallback(andj);
  58880. }
  58881. }
  58882. else {
  58883. result = andj === "true" ? true : false;
  58884. }
  58885. if (!result) {
  58886. ori = "false";
  58887. break;
  58888. }
  58889. }
  58890. }
  58891. if (result || ori === "true") {
  58892. result = true;
  58893. break;
  58894. }
  58895. // result equals false (or undefined)
  58896. if (ori !== "true" && ori !== "false") {
  58897. if (ori[0] === "!") {
  58898. result = !evaluateCallback(ori.substring(1));
  58899. }
  58900. else {
  58901. result = evaluateCallback(ori);
  58902. }
  58903. }
  58904. else {
  58905. result = ori === "true" ? true : false;
  58906. }
  58907. }
  58908. }
  58909. // the whole parenthesis scope is replaced by 'true' or 'false'
  58910. return result ? "true" : "false";
  58911. };
  58912. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  58913. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  58914. // remove whitespaces
  58915. r = r.replace(/[\s]/g, function () { return ""; });
  58916. return r.length % 2 ? "!" : "";
  58917. });
  58918. booleanString = booleanString.trim();
  58919. if (booleanString === "!true") {
  58920. booleanString = "false";
  58921. }
  58922. else if (booleanString === "!false") {
  58923. booleanString = "true";
  58924. }
  58925. return booleanString;
  58926. };
  58927. return AndOrNotEvaluator;
  58928. }());
  58929. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  58930. })(BABYLON || (BABYLON = {}));
  58931. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  58932. var BABYLON;
  58933. (function (BABYLON) {
  58934. var Database = /** @class */ (function () {
  58935. function Database(urlToScene, callbackManifestChecked) {
  58936. // Handling various flavors of prefixed version of IndexedDB
  58937. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  58938. this.callbackManifestChecked = callbackManifestChecked;
  58939. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  58940. this.db = null;
  58941. this._enableSceneOffline = false;
  58942. this._enableTexturesOffline = false;
  58943. this.manifestVersionFound = 0;
  58944. this.mustUpdateRessources = false;
  58945. this.hasReachedQuota = false;
  58946. if (!Database.IDBStorageEnabled) {
  58947. this.callbackManifestChecked(true);
  58948. }
  58949. else {
  58950. this.checkManifestFile();
  58951. }
  58952. }
  58953. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  58954. get: function () {
  58955. return this._enableSceneOffline;
  58956. },
  58957. enumerable: true,
  58958. configurable: true
  58959. });
  58960. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  58961. get: function () {
  58962. return this._enableTexturesOffline;
  58963. },
  58964. enumerable: true,
  58965. configurable: true
  58966. });
  58967. Database.prototype.checkManifestFile = function () {
  58968. var _this = this;
  58969. var noManifestFile = function () {
  58970. _this._enableSceneOffline = false;
  58971. _this._enableTexturesOffline = false;
  58972. _this.callbackManifestChecked(false);
  58973. };
  58974. var timeStampUsed = false;
  58975. var manifestURL = this.currentSceneUrl + ".manifest";
  58976. var xhr = new XMLHttpRequest();
  58977. if (navigator.onLine) {
  58978. // Adding a timestamp to by-pass browsers' cache
  58979. timeStampUsed = true;
  58980. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  58981. }
  58982. xhr.open("GET", manifestURL, true);
  58983. xhr.addEventListener("load", function () {
  58984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58985. try {
  58986. var manifestFile = JSON.parse(xhr.response);
  58987. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  58988. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  58989. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  58990. _this.manifestVersionFound = manifestFile.version;
  58991. }
  58992. if (_this.callbackManifestChecked) {
  58993. _this.callbackManifestChecked(true);
  58994. }
  58995. }
  58996. catch (ex) {
  58997. noManifestFile();
  58998. }
  58999. }
  59000. else {
  59001. noManifestFile();
  59002. }
  59003. }, false);
  59004. xhr.addEventListener("error", function (event) {
  59005. if (timeStampUsed) {
  59006. timeStampUsed = false;
  59007. // Let's retry without the timeStamp
  59008. // It could fail when coupled with HTML5 Offline API
  59009. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  59010. xhr.open("GET", retryManifestURL, true);
  59011. xhr.send();
  59012. }
  59013. else {
  59014. noManifestFile();
  59015. }
  59016. }, false);
  59017. try {
  59018. xhr.send();
  59019. }
  59020. catch (ex) {
  59021. BABYLON.Tools.Error("Error on XHR send request.");
  59022. this.callbackManifestChecked(false);
  59023. }
  59024. };
  59025. Database.prototype.openAsync = function (successCallback, errorCallback) {
  59026. var _this = this;
  59027. var handleError = function () {
  59028. _this.isSupported = false;
  59029. if (errorCallback)
  59030. errorCallback();
  59031. };
  59032. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  59033. // Your browser doesn't support IndexedDB
  59034. this.isSupported = false;
  59035. if (errorCallback)
  59036. errorCallback();
  59037. }
  59038. else {
  59039. // If the DB hasn't been opened or created yet
  59040. if (!this.db) {
  59041. this.hasReachedQuota = false;
  59042. this.isSupported = true;
  59043. var request = this.idbFactory.open("babylonjs", 1);
  59044. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  59045. request.onerror = function (event) {
  59046. handleError();
  59047. };
  59048. // executes when a version change transaction cannot complete due to other active transactions
  59049. request.onblocked = function (event) {
  59050. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  59051. handleError();
  59052. };
  59053. // DB has been opened successfully
  59054. request.onsuccess = function (event) {
  59055. _this.db = request.result;
  59056. successCallback();
  59057. };
  59058. // Initialization of the DB. Creating Scenes & Textures stores
  59059. request.onupgradeneeded = function (event) {
  59060. _this.db = (event.target).result;
  59061. if (_this.db) {
  59062. try {
  59063. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  59064. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  59065. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  59066. }
  59067. catch (ex) {
  59068. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  59069. handleError();
  59070. }
  59071. }
  59072. };
  59073. }
  59074. else {
  59075. if (successCallback)
  59076. successCallback();
  59077. }
  59078. }
  59079. };
  59080. Database.prototype.loadImageFromDB = function (url, image) {
  59081. var _this = this;
  59082. var completeURL = Database.ReturnFullUrlLocation(url);
  59083. var saveAndLoadImage = function () {
  59084. if (!_this.hasReachedQuota && _this.db !== null) {
  59085. // the texture is not yet in the DB, let's try to save it
  59086. _this._saveImageIntoDBAsync(completeURL, image);
  59087. }
  59088. else {
  59089. image.src = url;
  59090. }
  59091. };
  59092. if (!this.mustUpdateRessources) {
  59093. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  59094. }
  59095. else {
  59096. saveAndLoadImage();
  59097. }
  59098. };
  59099. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  59100. if (this.isSupported && this.db !== null) {
  59101. var texture;
  59102. var transaction = this.db.transaction(["textures"]);
  59103. transaction.onabort = function (event) {
  59104. image.src = url;
  59105. };
  59106. transaction.oncomplete = function (event) {
  59107. var blobTextureURL;
  59108. if (texture) {
  59109. var URL = window.URL || window.webkitURL;
  59110. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  59111. image.onerror = function () {
  59112. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  59113. image.src = url;
  59114. };
  59115. image.src = blobTextureURL;
  59116. }
  59117. else {
  59118. notInDBCallback();
  59119. }
  59120. };
  59121. var getRequest = transaction.objectStore("textures").get(url);
  59122. getRequest.onsuccess = function (event) {
  59123. texture = (event.target).result;
  59124. };
  59125. getRequest.onerror = function (event) {
  59126. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  59127. image.src = url;
  59128. };
  59129. }
  59130. else {
  59131. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59132. image.src = url;
  59133. }
  59134. };
  59135. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  59136. var _this = this;
  59137. if (this.isSupported) {
  59138. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  59139. var generateBlobUrl = function () {
  59140. var blobTextureURL;
  59141. if (blob) {
  59142. var URL = window.URL || window.webkitURL;
  59143. try {
  59144. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  59145. }
  59146. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  59147. catch (ex) {
  59148. blobTextureURL = URL.createObjectURL(blob);
  59149. }
  59150. }
  59151. if (blobTextureURL) {
  59152. image.src = blobTextureURL;
  59153. }
  59154. };
  59155. if (Database.IsUASupportingBlobStorage) {
  59156. var xhr = new XMLHttpRequest(), blob;
  59157. xhr.open("GET", url, true);
  59158. xhr.responseType = "blob";
  59159. xhr.addEventListener("load", function () {
  59160. if (xhr.status === 200 && _this.db) {
  59161. // Blob as response (XHR2)
  59162. blob = xhr.response;
  59163. var transaction = _this.db.transaction(["textures"], "readwrite");
  59164. // the transaction could abort because of a QuotaExceededError error
  59165. transaction.onabort = function (event) {
  59166. try {
  59167. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59168. var srcElement = (event.srcElement || event.target);
  59169. var error = srcElement.error;
  59170. if (error && error.name === "QuotaExceededError") {
  59171. _this.hasReachedQuota = true;
  59172. }
  59173. }
  59174. catch (ex) { }
  59175. generateBlobUrl();
  59176. };
  59177. transaction.oncomplete = function (event) {
  59178. generateBlobUrl();
  59179. };
  59180. var newTexture = { textureUrl: url, data: blob };
  59181. try {
  59182. // Put the blob into the dabase
  59183. var addRequest = transaction.objectStore("textures").put(newTexture);
  59184. addRequest.onsuccess = function (event) {
  59185. };
  59186. addRequest.onerror = function (event) {
  59187. generateBlobUrl();
  59188. };
  59189. }
  59190. catch (ex) {
  59191. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  59192. if (ex.code === 25) {
  59193. Database.IsUASupportingBlobStorage = false;
  59194. }
  59195. image.src = url;
  59196. }
  59197. }
  59198. else {
  59199. image.src = url;
  59200. }
  59201. }, false);
  59202. xhr.addEventListener("error", function (event) {
  59203. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  59204. image.src = url;
  59205. }, false);
  59206. xhr.send();
  59207. }
  59208. else {
  59209. image.src = url;
  59210. }
  59211. }
  59212. else {
  59213. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59214. image.src = url;
  59215. }
  59216. };
  59217. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  59218. var _this = this;
  59219. var updateVersion = function () {
  59220. // the version is not yet in the DB or we need to update it
  59221. _this._saveVersionIntoDBAsync(url, versionLoaded);
  59222. };
  59223. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  59224. };
  59225. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  59226. var _this = this;
  59227. if (this.isSupported && this.db) {
  59228. var version;
  59229. try {
  59230. var transaction = this.db.transaction(["versions"]);
  59231. transaction.oncomplete = function (event) {
  59232. if (version) {
  59233. // If the version in the JSON file is > than the version in DB
  59234. if (_this.manifestVersionFound > version.data) {
  59235. _this.mustUpdateRessources = true;
  59236. updateInDBCallback();
  59237. }
  59238. else {
  59239. callback(version.data);
  59240. }
  59241. }
  59242. else {
  59243. _this.mustUpdateRessources = true;
  59244. updateInDBCallback();
  59245. }
  59246. };
  59247. transaction.onabort = function (event) {
  59248. callback(-1);
  59249. };
  59250. var getRequest = transaction.objectStore("versions").get(url);
  59251. getRequest.onsuccess = function (event) {
  59252. version = (event.target).result;
  59253. };
  59254. getRequest.onerror = function (event) {
  59255. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  59256. callback(-1);
  59257. };
  59258. }
  59259. catch (ex) {
  59260. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  59261. callback(-1);
  59262. }
  59263. }
  59264. else {
  59265. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59266. callback(-1);
  59267. }
  59268. };
  59269. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  59270. var _this = this;
  59271. if (this.isSupported && !this.hasReachedQuota && this.db) {
  59272. try {
  59273. // Open a transaction to the database
  59274. var transaction = this.db.transaction(["versions"], "readwrite");
  59275. // the transaction could abort because of a QuotaExceededError error
  59276. transaction.onabort = function (event) {
  59277. try {
  59278. var error = event.srcElement['error'];
  59279. if (error && error.name === "QuotaExceededError") {
  59280. _this.hasReachedQuota = true;
  59281. }
  59282. }
  59283. catch (ex) { }
  59284. callback(-1);
  59285. };
  59286. transaction.oncomplete = function (event) {
  59287. callback(_this.manifestVersionFound);
  59288. };
  59289. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  59290. // Put the scene into the database
  59291. var addRequest = transaction.objectStore("versions").put(newVersion);
  59292. addRequest.onsuccess = function (event) {
  59293. };
  59294. addRequest.onerror = function (event) {
  59295. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  59296. };
  59297. }
  59298. catch (ex) {
  59299. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  59300. callback(-1);
  59301. }
  59302. }
  59303. else {
  59304. callback(-1);
  59305. }
  59306. };
  59307. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  59308. var _this = this;
  59309. var completeUrl = Database.ReturnFullUrlLocation(url);
  59310. var saveAndLoadFile = function () {
  59311. // the scene is not yet in the DB, let's try to save it
  59312. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  59313. };
  59314. this._checkVersionFromDB(completeUrl, function (version) {
  59315. if (version !== -1) {
  59316. if (!_this.mustUpdateRessources) {
  59317. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  59318. }
  59319. else {
  59320. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  59321. }
  59322. }
  59323. else {
  59324. if (errorCallback) {
  59325. errorCallback();
  59326. }
  59327. }
  59328. });
  59329. };
  59330. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  59331. if (this.isSupported && this.db) {
  59332. var targetStore;
  59333. if (url.indexOf(".babylon") !== -1) {
  59334. targetStore = "scenes";
  59335. }
  59336. else {
  59337. targetStore = "textures";
  59338. }
  59339. var file;
  59340. var transaction = this.db.transaction([targetStore]);
  59341. transaction.oncomplete = function (event) {
  59342. if (file) {
  59343. callback(file.data);
  59344. }
  59345. else {
  59346. notInDBCallback();
  59347. }
  59348. };
  59349. transaction.onabort = function (event) {
  59350. notInDBCallback();
  59351. };
  59352. var getRequest = transaction.objectStore(targetStore).get(url);
  59353. getRequest.onsuccess = function (event) {
  59354. file = (event.target).result;
  59355. };
  59356. getRequest.onerror = function (event) {
  59357. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  59358. notInDBCallback();
  59359. };
  59360. }
  59361. else {
  59362. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59363. callback();
  59364. }
  59365. };
  59366. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  59367. var _this = this;
  59368. if (this.isSupported) {
  59369. var targetStore;
  59370. if (url.indexOf(".babylon") !== -1) {
  59371. targetStore = "scenes";
  59372. }
  59373. else {
  59374. targetStore = "textures";
  59375. }
  59376. // Create XHR
  59377. var xhr = new XMLHttpRequest();
  59378. var fileData;
  59379. xhr.open("GET", url, true);
  59380. if (useArrayBuffer) {
  59381. xhr.responseType = "arraybuffer";
  59382. }
  59383. if (progressCallback) {
  59384. xhr.onprogress = progressCallback;
  59385. }
  59386. xhr.addEventListener("load", function () {
  59387. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  59388. // Blob as response (XHR2)
  59389. //fileData = xhr.responseText;
  59390. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  59391. if (!_this.hasReachedQuota && _this.db) {
  59392. // Open a transaction to the database
  59393. var transaction = _this.db.transaction([targetStore], "readwrite");
  59394. // the transaction could abort because of a QuotaExceededError error
  59395. transaction.onabort = function (event) {
  59396. try {
  59397. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59398. var error = event.srcElement['error'];
  59399. if (error && error.name === "QuotaExceededError") {
  59400. _this.hasReachedQuota = true;
  59401. }
  59402. }
  59403. catch (ex) { }
  59404. callback(fileData);
  59405. };
  59406. transaction.oncomplete = function (event) {
  59407. callback(fileData);
  59408. };
  59409. var newFile;
  59410. if (targetStore === "scenes") {
  59411. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  59412. }
  59413. else {
  59414. newFile = { textureUrl: url, data: fileData };
  59415. }
  59416. try {
  59417. // Put the scene into the database
  59418. var addRequest = transaction.objectStore(targetStore).put(newFile);
  59419. addRequest.onsuccess = function (event) {
  59420. };
  59421. addRequest.onerror = function (event) {
  59422. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  59423. };
  59424. }
  59425. catch (ex) {
  59426. callback(fileData);
  59427. }
  59428. }
  59429. else {
  59430. callback(fileData);
  59431. }
  59432. }
  59433. else {
  59434. callback();
  59435. }
  59436. }, false);
  59437. xhr.addEventListener("error", function (event) {
  59438. BABYLON.Tools.Error("error on XHR request.");
  59439. callback();
  59440. }, false);
  59441. xhr.send();
  59442. }
  59443. else {
  59444. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59445. callback();
  59446. }
  59447. };
  59448. Database.IsUASupportingBlobStorage = true;
  59449. Database.IDBStorageEnabled = true;
  59450. Database.parseURL = function (url) {
  59451. var a = document.createElement('a');
  59452. a.href = url;
  59453. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  59454. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  59455. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  59456. return absLocation;
  59457. };
  59458. Database.ReturnFullUrlLocation = function (url) {
  59459. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  59460. return (Database.parseURL(window.location.href) + url);
  59461. }
  59462. else {
  59463. return url;
  59464. }
  59465. };
  59466. return Database;
  59467. }());
  59468. BABYLON.Database = Database;
  59469. })(BABYLON || (BABYLON = {}));
  59470. //# sourceMappingURL=babylon.database.js.map
  59471. var BABYLON;
  59472. (function (BABYLON) {
  59473. var FresnelParameters = /** @class */ (function () {
  59474. function FresnelParameters() {
  59475. this._isEnabled = true;
  59476. this.leftColor = BABYLON.Color3.White();
  59477. this.rightColor = BABYLON.Color3.Black();
  59478. this.bias = 0;
  59479. this.power = 1;
  59480. }
  59481. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  59482. get: function () {
  59483. return this._isEnabled;
  59484. },
  59485. set: function (value) {
  59486. if (this._isEnabled === value) {
  59487. return;
  59488. }
  59489. this._isEnabled = value;
  59490. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  59491. },
  59492. enumerable: true,
  59493. configurable: true
  59494. });
  59495. FresnelParameters.prototype.clone = function () {
  59496. var newFresnelParameters = new FresnelParameters();
  59497. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  59498. return newFresnelParameters;
  59499. };
  59500. FresnelParameters.prototype.serialize = function () {
  59501. var serializationObject = {};
  59502. serializationObject.isEnabled = this.isEnabled;
  59503. serializationObject.leftColor = this.leftColor;
  59504. serializationObject.rightColor = this.rightColor;
  59505. serializationObject.bias = this.bias;
  59506. serializationObject.power = this.power;
  59507. return serializationObject;
  59508. };
  59509. FresnelParameters.Parse = function (parsedFresnelParameters) {
  59510. var fresnelParameters = new FresnelParameters();
  59511. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  59512. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  59513. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  59514. fresnelParameters.bias = parsedFresnelParameters.bias;
  59515. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  59516. return fresnelParameters;
  59517. };
  59518. return FresnelParameters;
  59519. }());
  59520. BABYLON.FresnelParameters = FresnelParameters;
  59521. })(BABYLON || (BABYLON = {}));
  59522. //# sourceMappingURL=babylon.fresnelParameters.js.map
  59523. var BABYLON;
  59524. (function (BABYLON) {
  59525. var MultiMaterial = /** @class */ (function (_super) {
  59526. __extends(MultiMaterial, _super);
  59527. function MultiMaterial(name, scene) {
  59528. var _this = _super.call(this, name, scene, true) || this;
  59529. scene.multiMaterials.push(_this);
  59530. _this.subMaterials = new Array();
  59531. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  59532. return _this;
  59533. }
  59534. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  59535. get: function () {
  59536. return this._subMaterials;
  59537. },
  59538. set: function (value) {
  59539. this._subMaterials = value;
  59540. this._hookArray(value);
  59541. },
  59542. enumerable: true,
  59543. configurable: true
  59544. });
  59545. MultiMaterial.prototype._hookArray = function (array) {
  59546. var _this = this;
  59547. var oldPush = array.push;
  59548. array.push = function () {
  59549. var items = [];
  59550. for (var _i = 0; _i < arguments.length; _i++) {
  59551. items[_i] = arguments[_i];
  59552. }
  59553. var result = oldPush.apply(array, items);
  59554. _this._markAllSubMeshesAsTexturesDirty();
  59555. return result;
  59556. };
  59557. var oldSplice = array.splice;
  59558. array.splice = function (index, deleteCount) {
  59559. var deleted = oldSplice.apply(array, [index, deleteCount]);
  59560. _this._markAllSubMeshesAsTexturesDirty();
  59561. return deleted;
  59562. };
  59563. };
  59564. // Properties
  59565. MultiMaterial.prototype.getSubMaterial = function (index) {
  59566. if (index < 0 || index >= this.subMaterials.length) {
  59567. return this.getScene().defaultMaterial;
  59568. }
  59569. return this.subMaterials[index];
  59570. };
  59571. MultiMaterial.prototype.getActiveTextures = function () {
  59572. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  59573. if (subMaterial) {
  59574. return subMaterial.getActiveTextures();
  59575. }
  59576. else {
  59577. return [];
  59578. }
  59579. }));
  59580. var _a;
  59581. };
  59582. // Methods
  59583. MultiMaterial.prototype.getClassName = function () {
  59584. return "MultiMaterial";
  59585. };
  59586. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  59587. for (var index = 0; index < this.subMaterials.length; index++) {
  59588. var subMaterial = this.subMaterials[index];
  59589. if (subMaterial) {
  59590. if (subMaterial.storeEffectOnSubMeshes) {
  59591. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  59592. return false;
  59593. }
  59594. continue;
  59595. }
  59596. if (!subMaterial.isReady(mesh)) {
  59597. return false;
  59598. }
  59599. }
  59600. }
  59601. return true;
  59602. };
  59603. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  59604. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  59605. for (var index = 0; index < this.subMaterials.length; index++) {
  59606. var subMaterial = null;
  59607. var current = this.subMaterials[index];
  59608. if (cloneChildren && current) {
  59609. subMaterial = current.clone(name + "-" + current.name);
  59610. }
  59611. else {
  59612. subMaterial = this.subMaterials[index];
  59613. }
  59614. newMultiMaterial.subMaterials.push(subMaterial);
  59615. }
  59616. return newMultiMaterial;
  59617. };
  59618. MultiMaterial.prototype.serialize = function () {
  59619. var serializationObject = {};
  59620. serializationObject.name = this.name;
  59621. serializationObject.id = this.id;
  59622. if (BABYLON.Tags) {
  59623. serializationObject.tags = BABYLON.Tags.GetTags(this);
  59624. }
  59625. serializationObject.materials = [];
  59626. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  59627. var subMat = this.subMaterials[matIndex];
  59628. if (subMat) {
  59629. serializationObject.materials.push(subMat.id);
  59630. }
  59631. else {
  59632. serializationObject.materials.push(null);
  59633. }
  59634. }
  59635. return serializationObject;
  59636. };
  59637. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59638. var scene = this.getScene();
  59639. if (!scene) {
  59640. return;
  59641. }
  59642. var index = scene.multiMaterials.indexOf(this);
  59643. if (index >= 0) {
  59644. scene.multiMaterials.splice(index, 1);
  59645. }
  59646. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59647. };
  59648. return MultiMaterial;
  59649. }(BABYLON.Material));
  59650. BABYLON.MultiMaterial = MultiMaterial;
  59651. })(BABYLON || (BABYLON = {}));
  59652. //# sourceMappingURL=babylon.multiMaterial.js.map
  59653. var BABYLON;
  59654. (function (BABYLON) {
  59655. var FreeCameraTouchInput = /** @class */ (function () {
  59656. function FreeCameraTouchInput() {
  59657. this._offsetX = null;
  59658. this._offsetY = null;
  59659. this._pointerPressed = new Array();
  59660. this.touchAngularSensibility = 200000.0;
  59661. this.touchMoveSensibility = 250.0;
  59662. }
  59663. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  59664. var _this = this;
  59665. var previousPosition = null;
  59666. if (this._pointerInput === undefined) {
  59667. this._onLostFocus = function (evt) {
  59668. _this._offsetX = null;
  59669. _this._offsetY = null;
  59670. };
  59671. this._pointerInput = function (p, s) {
  59672. var evt = p.event;
  59673. if (evt.pointerType === "mouse") {
  59674. return;
  59675. }
  59676. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  59677. if (!noPreventDefault) {
  59678. evt.preventDefault();
  59679. }
  59680. _this._pointerPressed.push(evt.pointerId);
  59681. if (_this._pointerPressed.length !== 1) {
  59682. return;
  59683. }
  59684. previousPosition = {
  59685. x: evt.clientX,
  59686. y: evt.clientY
  59687. };
  59688. }
  59689. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  59690. if (!noPreventDefault) {
  59691. evt.preventDefault();
  59692. }
  59693. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59694. if (index === -1) {
  59695. return;
  59696. }
  59697. _this._pointerPressed.splice(index, 1);
  59698. if (index != 0) {
  59699. return;
  59700. }
  59701. previousPosition = null;
  59702. _this._offsetX = null;
  59703. _this._offsetY = null;
  59704. }
  59705. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  59706. if (!noPreventDefault) {
  59707. evt.preventDefault();
  59708. }
  59709. if (!previousPosition) {
  59710. return;
  59711. }
  59712. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59713. if (index != 0) {
  59714. return;
  59715. }
  59716. _this._offsetX = evt.clientX - previousPosition.x;
  59717. _this._offsetY = -(evt.clientY - previousPosition.y);
  59718. }
  59719. };
  59720. }
  59721. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  59722. if (this._onLostFocus) {
  59723. element.addEventListener("blur", this._onLostFocus);
  59724. }
  59725. };
  59726. FreeCameraTouchInput.prototype.detachControl = function (element) {
  59727. if (this._pointerInput && element) {
  59728. if (this._observer) {
  59729. this.camera.getScene().onPointerObservable.remove(this._observer);
  59730. this._observer = null;
  59731. }
  59732. if (this._onLostFocus) {
  59733. element.removeEventListener("blur", this._onLostFocus);
  59734. this._onLostFocus = null;
  59735. }
  59736. this._pointerPressed = [];
  59737. this._offsetX = null;
  59738. this._offsetY = null;
  59739. }
  59740. };
  59741. FreeCameraTouchInput.prototype.checkInputs = function () {
  59742. if (this._offsetX && this._offsetY) {
  59743. var camera = this.camera;
  59744. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  59745. if (this._pointerPressed.length > 1) {
  59746. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  59747. }
  59748. else {
  59749. var speed = camera._computeLocalCameraSpeed();
  59750. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  59751. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  59752. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  59753. }
  59754. }
  59755. };
  59756. FreeCameraTouchInput.prototype.getClassName = function () {
  59757. return "FreeCameraTouchInput";
  59758. };
  59759. FreeCameraTouchInput.prototype.getSimpleName = function () {
  59760. return "touch";
  59761. };
  59762. __decorate([
  59763. BABYLON.serialize()
  59764. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  59765. __decorate([
  59766. BABYLON.serialize()
  59767. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  59768. return FreeCameraTouchInput;
  59769. }());
  59770. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  59771. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  59772. })(BABYLON || (BABYLON = {}));
  59773. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  59774. var BABYLON;
  59775. (function (BABYLON) {
  59776. // We're mainly based on the logic defined into the FreeCamera code
  59777. var TouchCamera = /** @class */ (function (_super) {
  59778. __extends(TouchCamera, _super);
  59779. //-- end properties for backward compatibility for inputs
  59780. function TouchCamera(name, position, scene) {
  59781. var _this = _super.call(this, name, position, scene) || this;
  59782. _this.inputs.addTouch();
  59783. _this._setupInputs();
  59784. return _this;
  59785. }
  59786. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  59787. //-- Begin properties for backward compatibility for inputs
  59788. get: function () {
  59789. var touch = this.inputs.attached["touch"];
  59790. if (touch)
  59791. return touch.touchAngularSensibility;
  59792. return 0;
  59793. },
  59794. set: function (value) {
  59795. var touch = this.inputs.attached["touch"];
  59796. if (touch)
  59797. touch.touchAngularSensibility = value;
  59798. },
  59799. enumerable: true,
  59800. configurable: true
  59801. });
  59802. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  59803. get: function () {
  59804. var touch = this.inputs.attached["touch"];
  59805. if (touch)
  59806. return touch.touchMoveSensibility;
  59807. return 0;
  59808. },
  59809. set: function (value) {
  59810. var touch = this.inputs.attached["touch"];
  59811. if (touch)
  59812. touch.touchMoveSensibility = value;
  59813. },
  59814. enumerable: true,
  59815. configurable: true
  59816. });
  59817. TouchCamera.prototype.getClassName = function () {
  59818. return "TouchCamera";
  59819. };
  59820. TouchCamera.prototype._setupInputs = function () {
  59821. var mouse = this.inputs.attached["mouse"];
  59822. if (mouse) {
  59823. mouse.touchEnabled = false;
  59824. }
  59825. };
  59826. return TouchCamera;
  59827. }(BABYLON.FreeCamera));
  59828. BABYLON.TouchCamera = TouchCamera;
  59829. })(BABYLON || (BABYLON = {}));
  59830. //# sourceMappingURL=babylon.touchCamera.js.map
  59831. var BABYLON;
  59832. (function (BABYLON) {
  59833. var ProceduralTexture = /** @class */ (function (_super) {
  59834. __extends(ProceduralTexture, _super);
  59835. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  59836. if (fallbackTexture === void 0) { fallbackTexture = null; }
  59837. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59838. if (isCube === void 0) { isCube = false; }
  59839. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59840. _this.isCube = isCube;
  59841. _this.isEnabled = true;
  59842. _this._currentRefreshId = -1;
  59843. _this._refreshRate = 1;
  59844. _this._vertexBuffers = {};
  59845. _this._uniforms = new Array();
  59846. _this._samplers = new Array();
  59847. _this._textures = {};
  59848. _this._floats = {};
  59849. _this._floatsArrays = {};
  59850. _this._colors3 = {};
  59851. _this._colors4 = {};
  59852. _this._vectors2 = {};
  59853. _this._vectors3 = {};
  59854. _this._matrices = {};
  59855. _this._fallbackTextureUsed = false;
  59856. scene._proceduralTextures.push(_this);
  59857. _this._engine = scene.getEngine();
  59858. _this.name = name;
  59859. _this.isRenderTarget = true;
  59860. _this._size = size;
  59861. _this._generateMipMaps = generateMipMaps;
  59862. _this.setFragment(fragment);
  59863. _this._fallbackTexture = fallbackTexture;
  59864. if (isCube) {
  59865. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  59866. _this.setFloat("face", 0);
  59867. }
  59868. else {
  59869. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  59870. }
  59871. // VBO
  59872. var vertices = [];
  59873. vertices.push(1, 1);
  59874. vertices.push(-1, 1);
  59875. vertices.push(-1, -1);
  59876. vertices.push(1, -1);
  59877. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59878. _this._createIndexBuffer();
  59879. return _this;
  59880. }
  59881. ProceduralTexture.prototype._createIndexBuffer = function () {
  59882. var engine = this._engine;
  59883. // Indices
  59884. var indices = [];
  59885. indices.push(0);
  59886. indices.push(1);
  59887. indices.push(2);
  59888. indices.push(0);
  59889. indices.push(2);
  59890. indices.push(3);
  59891. this._indexBuffer = engine.createIndexBuffer(indices);
  59892. };
  59893. ProceduralTexture.prototype._rebuild = function () {
  59894. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59895. if (vb) {
  59896. vb._rebuild();
  59897. }
  59898. this._createIndexBuffer();
  59899. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59900. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59901. }
  59902. };
  59903. ProceduralTexture.prototype.reset = function () {
  59904. if (this._effect === undefined) {
  59905. return;
  59906. }
  59907. var engine = this._engine;
  59908. engine._releaseEffect(this._effect);
  59909. };
  59910. ProceduralTexture.prototype.isReady = function () {
  59911. var _this = this;
  59912. var engine = this._engine;
  59913. var shaders;
  59914. if (!this._fragment) {
  59915. return false;
  59916. }
  59917. if (this._fallbackTextureUsed) {
  59918. return true;
  59919. }
  59920. if (this._fragment.fragmentElement !== undefined) {
  59921. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  59922. }
  59923. else {
  59924. shaders = { vertex: "procedural", fragment: this._fragment };
  59925. }
  59926. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  59927. _this.releaseInternalTexture();
  59928. if (_this._fallbackTexture) {
  59929. _this._texture = _this._fallbackTexture._texture;
  59930. if (_this._texture) {
  59931. _this._texture.incrementReferences();
  59932. }
  59933. }
  59934. _this._fallbackTextureUsed = true;
  59935. });
  59936. return this._effect.isReady();
  59937. };
  59938. ProceduralTexture.prototype.resetRefreshCounter = function () {
  59939. this._currentRefreshId = -1;
  59940. };
  59941. ProceduralTexture.prototype.setFragment = function (fragment) {
  59942. this._fragment = fragment;
  59943. };
  59944. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  59945. get: function () {
  59946. return this._refreshRate;
  59947. },
  59948. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59949. set: function (value) {
  59950. this._refreshRate = value;
  59951. this.resetRefreshCounter();
  59952. },
  59953. enumerable: true,
  59954. configurable: true
  59955. });
  59956. ProceduralTexture.prototype._shouldRender = function () {
  59957. if (!this.isEnabled || !this.isReady() || !this._texture) {
  59958. return false;
  59959. }
  59960. if (this._fallbackTextureUsed) {
  59961. return false;
  59962. }
  59963. if (this._currentRefreshId === -1) {
  59964. this._currentRefreshId = 1;
  59965. return true;
  59966. }
  59967. if (this.refreshRate === this._currentRefreshId) {
  59968. this._currentRefreshId = 1;
  59969. return true;
  59970. }
  59971. this._currentRefreshId++;
  59972. return false;
  59973. };
  59974. ProceduralTexture.prototype.getRenderSize = function () {
  59975. return this._size;
  59976. };
  59977. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  59978. if (this._fallbackTextureUsed) {
  59979. return;
  59980. }
  59981. this.releaseInternalTexture();
  59982. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  59983. };
  59984. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  59985. if (this._uniforms.indexOf(uniformName) === -1) {
  59986. this._uniforms.push(uniformName);
  59987. }
  59988. };
  59989. ProceduralTexture.prototype.setTexture = function (name, texture) {
  59990. if (this._samplers.indexOf(name) === -1) {
  59991. this._samplers.push(name);
  59992. }
  59993. this._textures[name] = texture;
  59994. return this;
  59995. };
  59996. ProceduralTexture.prototype.setFloat = function (name, value) {
  59997. this._checkUniform(name);
  59998. this._floats[name] = value;
  59999. return this;
  60000. };
  60001. ProceduralTexture.prototype.setFloats = function (name, value) {
  60002. this._checkUniform(name);
  60003. this._floatsArrays[name] = value;
  60004. return this;
  60005. };
  60006. ProceduralTexture.prototype.setColor3 = function (name, value) {
  60007. this._checkUniform(name);
  60008. this._colors3[name] = value;
  60009. return this;
  60010. };
  60011. ProceduralTexture.prototype.setColor4 = function (name, value) {
  60012. this._checkUniform(name);
  60013. this._colors4[name] = value;
  60014. return this;
  60015. };
  60016. ProceduralTexture.prototype.setVector2 = function (name, value) {
  60017. this._checkUniform(name);
  60018. this._vectors2[name] = value;
  60019. return this;
  60020. };
  60021. ProceduralTexture.prototype.setVector3 = function (name, value) {
  60022. this._checkUniform(name);
  60023. this._vectors3[name] = value;
  60024. return this;
  60025. };
  60026. ProceduralTexture.prototype.setMatrix = function (name, value) {
  60027. this._checkUniform(name);
  60028. this._matrices[name] = value;
  60029. return this;
  60030. };
  60031. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60032. var scene = this.getScene();
  60033. if (!scene) {
  60034. return;
  60035. }
  60036. var engine = this._engine;
  60037. // Render
  60038. engine.enableEffect(this._effect);
  60039. engine.setState(false);
  60040. // Texture
  60041. for (var name in this._textures) {
  60042. this._effect.setTexture(name, this._textures[name]);
  60043. }
  60044. // Float
  60045. for (name in this._floats) {
  60046. this._effect.setFloat(name, this._floats[name]);
  60047. }
  60048. // Floats
  60049. for (name in this._floatsArrays) {
  60050. this._effect.setArray(name, this._floatsArrays[name]);
  60051. }
  60052. // Color3
  60053. for (name in this._colors3) {
  60054. this._effect.setColor3(name, this._colors3[name]);
  60055. }
  60056. // Color4
  60057. for (name in this._colors4) {
  60058. var color = this._colors4[name];
  60059. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60060. }
  60061. // Vector2
  60062. for (name in this._vectors2) {
  60063. this._effect.setVector2(name, this._vectors2[name]);
  60064. }
  60065. // Vector3
  60066. for (name in this._vectors3) {
  60067. this._effect.setVector3(name, this._vectors3[name]);
  60068. }
  60069. // Matrix
  60070. for (name in this._matrices) {
  60071. this._effect.setMatrix(name, this._matrices[name]);
  60072. }
  60073. if (!this._texture) {
  60074. return;
  60075. }
  60076. if (this.isCube) {
  60077. for (var face = 0; face < 6; face++) {
  60078. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  60079. // VBOs
  60080. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60081. this._effect.setFloat("face", face);
  60082. // Clear
  60083. engine.clear(scene.clearColor, true, true, true);
  60084. // Draw order
  60085. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60086. // Mipmaps
  60087. if (face === 5) {
  60088. engine.generateMipMapsForCubemap(this._texture);
  60089. }
  60090. }
  60091. }
  60092. else {
  60093. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  60094. // VBOs
  60095. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60096. // Clear
  60097. engine.clear(scene.clearColor, true, true, true);
  60098. // Draw order
  60099. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60100. }
  60101. // Unbind
  60102. engine.unBindFramebuffer(this._texture, this.isCube);
  60103. if (this.onGenerated) {
  60104. this.onGenerated();
  60105. }
  60106. };
  60107. ProceduralTexture.prototype.clone = function () {
  60108. var textureSize = this.getSize();
  60109. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  60110. // Base texture
  60111. newTexture.hasAlpha = this.hasAlpha;
  60112. newTexture.level = this.level;
  60113. // RenderTarget Texture
  60114. newTexture.coordinatesMode = this.coordinatesMode;
  60115. return newTexture;
  60116. };
  60117. ProceduralTexture.prototype.dispose = function () {
  60118. var scene = this.getScene();
  60119. if (!scene) {
  60120. return;
  60121. }
  60122. var index = scene._proceduralTextures.indexOf(this);
  60123. if (index >= 0) {
  60124. scene._proceduralTextures.splice(index, 1);
  60125. }
  60126. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60127. if (vertexBuffer) {
  60128. vertexBuffer.dispose();
  60129. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60130. }
  60131. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  60132. this._indexBuffer = null;
  60133. }
  60134. _super.prototype.dispose.call(this);
  60135. };
  60136. return ProceduralTexture;
  60137. }(BABYLON.Texture));
  60138. BABYLON.ProceduralTexture = ProceduralTexture;
  60139. })(BABYLON || (BABYLON = {}));
  60140. //# sourceMappingURL=babylon.proceduralTexture.js.map
  60141. var BABYLON;
  60142. (function (BABYLON) {
  60143. var CustomProceduralTexture = /** @class */ (function (_super) {
  60144. __extends(CustomProceduralTexture, _super);
  60145. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  60146. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  60147. _this._animate = true;
  60148. _this._time = 0;
  60149. _this._texturePath = texturePath;
  60150. //Try to load json
  60151. _this.loadJson(texturePath);
  60152. _this.refreshRate = 1;
  60153. return _this;
  60154. }
  60155. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  60156. var _this = this;
  60157. var noConfigFile = function () {
  60158. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  60159. try {
  60160. _this.setFragment(_this._texturePath);
  60161. }
  60162. catch (ex) {
  60163. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  60164. }
  60165. };
  60166. var configFileUrl = jsonUrl + "/config.json";
  60167. var xhr = new XMLHttpRequest();
  60168. xhr.open("GET", configFileUrl, true);
  60169. xhr.addEventListener("load", function () {
  60170. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60171. try {
  60172. _this._config = JSON.parse(xhr.response);
  60173. _this.updateShaderUniforms();
  60174. _this.updateTextures();
  60175. _this.setFragment(_this._texturePath + "/custom");
  60176. _this._animate = _this._config.animate;
  60177. _this.refreshRate = _this._config.refreshrate;
  60178. }
  60179. catch (ex) {
  60180. noConfigFile();
  60181. }
  60182. }
  60183. else {
  60184. noConfigFile();
  60185. }
  60186. }, false);
  60187. xhr.addEventListener("error", function () {
  60188. noConfigFile();
  60189. }, false);
  60190. try {
  60191. xhr.send();
  60192. }
  60193. catch (ex) {
  60194. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  60195. }
  60196. };
  60197. CustomProceduralTexture.prototype.isReady = function () {
  60198. if (!_super.prototype.isReady.call(this)) {
  60199. return false;
  60200. }
  60201. for (var name in this._textures) {
  60202. var texture = this._textures[name];
  60203. if (!texture.isReady()) {
  60204. return false;
  60205. }
  60206. }
  60207. return true;
  60208. };
  60209. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60210. var scene = this.getScene();
  60211. if (this._animate && scene) {
  60212. this._time += scene.getAnimationRatio() * 0.03;
  60213. this.updateShaderUniforms();
  60214. }
  60215. _super.prototype.render.call(this, useCameraPostProcess);
  60216. };
  60217. CustomProceduralTexture.prototype.updateTextures = function () {
  60218. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  60219. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  60220. }
  60221. };
  60222. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  60223. if (this._config) {
  60224. for (var j = 0; j < this._config.uniforms.length; j++) {
  60225. var uniform = this._config.uniforms[j];
  60226. switch (uniform.type) {
  60227. case "float":
  60228. this.setFloat(uniform.name, uniform.value);
  60229. break;
  60230. case "color3":
  60231. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  60232. break;
  60233. case "color4":
  60234. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  60235. break;
  60236. case "vector2":
  60237. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  60238. break;
  60239. case "vector3":
  60240. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  60241. break;
  60242. }
  60243. }
  60244. }
  60245. this.setFloat("time", this._time);
  60246. };
  60247. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  60248. get: function () {
  60249. return this._animate;
  60250. },
  60251. set: function (value) {
  60252. this._animate = value;
  60253. },
  60254. enumerable: true,
  60255. configurable: true
  60256. });
  60257. return CustomProceduralTexture;
  60258. }(BABYLON.ProceduralTexture));
  60259. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  60260. })(BABYLON || (BABYLON = {}));
  60261. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  60262. var BABYLON;
  60263. (function (BABYLON) {
  60264. var FreeCameraGamepadInput = /** @class */ (function () {
  60265. function FreeCameraGamepadInput() {
  60266. this.gamepadAngularSensibility = 200;
  60267. this.gamepadMoveSensibility = 40;
  60268. // private members
  60269. this._cameraTransform = BABYLON.Matrix.Identity();
  60270. this._deltaTransform = BABYLON.Vector3.Zero();
  60271. this._vector3 = BABYLON.Vector3.Zero();
  60272. this._vector2 = BABYLON.Vector2.Zero();
  60273. }
  60274. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60275. var _this = this;
  60276. var manager = this.camera.getScene().gamepadManager;
  60277. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60278. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60279. // prioritize XBOX gamepads.
  60280. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60281. _this.gamepad = gamepad;
  60282. }
  60283. }
  60284. });
  60285. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60286. if (_this.gamepad === gamepad) {
  60287. _this.gamepad = null;
  60288. }
  60289. });
  60290. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60291. };
  60292. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  60293. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60294. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60295. this.gamepad = null;
  60296. };
  60297. FreeCameraGamepadInput.prototype.checkInputs = function () {
  60298. if (this.gamepad && this.gamepad.leftStick) {
  60299. var camera = this.camera;
  60300. var LSValues = this.gamepad.leftStick;
  60301. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  60302. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60303. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  60304. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  60305. var RSValues = this.gamepad.rightStick;
  60306. if (RSValues) {
  60307. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  60308. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  60309. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  60310. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  60311. }
  60312. else {
  60313. RSValues = { x: 0, y: 0 };
  60314. }
  60315. if (!camera.rotationQuaternion) {
  60316. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  60317. }
  60318. else {
  60319. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  60320. }
  60321. var speed = camera._computeLocalCameraSpeed() * 50.0;
  60322. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  60323. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  60324. camera.cameraDirection.addInPlace(this._deltaTransform);
  60325. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  60326. camera.cameraRotation.addInPlace(this._vector2);
  60327. }
  60328. };
  60329. FreeCameraGamepadInput.prototype.getClassName = function () {
  60330. return "FreeCameraGamepadInput";
  60331. };
  60332. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  60333. return "gamepad";
  60334. };
  60335. __decorate([
  60336. BABYLON.serialize()
  60337. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  60338. __decorate([
  60339. BABYLON.serialize()
  60340. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60341. return FreeCameraGamepadInput;
  60342. }());
  60343. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  60344. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  60345. })(BABYLON || (BABYLON = {}));
  60346. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  60347. var BABYLON;
  60348. (function (BABYLON) {
  60349. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  60350. function ArcRotateCameraGamepadInput() {
  60351. this.gamepadRotationSensibility = 80;
  60352. this.gamepadMoveSensibility = 40;
  60353. }
  60354. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60355. var _this = this;
  60356. var manager = this.camera.getScene().gamepadManager;
  60357. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60358. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60359. // prioritize XBOX gamepads.
  60360. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60361. _this.gamepad = gamepad;
  60362. }
  60363. }
  60364. });
  60365. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60366. if (_this.gamepad === gamepad) {
  60367. _this.gamepad = null;
  60368. }
  60369. });
  60370. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60371. };
  60372. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  60373. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60374. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60375. this.gamepad = null;
  60376. };
  60377. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  60378. if (this.gamepad) {
  60379. var camera = this.camera;
  60380. var RSValues = this.gamepad.rightStick;
  60381. if (RSValues) {
  60382. if (RSValues.x != 0) {
  60383. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  60384. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  60385. camera.inertialAlphaOffset += normalizedRX;
  60386. }
  60387. }
  60388. if (RSValues.y != 0) {
  60389. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  60390. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  60391. camera.inertialBetaOffset += normalizedRY;
  60392. }
  60393. }
  60394. }
  60395. var LSValues = this.gamepad.leftStick;
  60396. if (LSValues && LSValues.y != 0) {
  60397. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60398. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  60399. this.camera.inertialRadiusOffset -= normalizedLY;
  60400. }
  60401. }
  60402. }
  60403. };
  60404. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  60405. return "ArcRotateCameraGamepadInput";
  60406. };
  60407. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  60408. return "gamepad";
  60409. };
  60410. __decorate([
  60411. BABYLON.serialize()
  60412. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  60413. __decorate([
  60414. BABYLON.serialize()
  60415. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60416. return ArcRotateCameraGamepadInput;
  60417. }());
  60418. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  60419. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  60420. })(BABYLON || (BABYLON = {}));
  60421. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  60422. var BABYLON;
  60423. (function (BABYLON) {
  60424. var GamepadManager = /** @class */ (function () {
  60425. function GamepadManager(_scene) {
  60426. var _this = this;
  60427. this._scene = _scene;
  60428. this._babylonGamepads = [];
  60429. this._oneGamepadConnected = false;
  60430. this._isMonitoring = false;
  60431. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  60432. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60433. this._gamepadEventSupported = false;
  60434. }
  60435. else {
  60436. this._gamepadEventSupported = 'GamepadEvent' in window;
  60437. this._gamepadSupport = (navigator.getGamepads ||
  60438. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  60439. }
  60440. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  60441. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  60442. for (var i in _this._babylonGamepads) {
  60443. var gamepad = _this._babylonGamepads[i];
  60444. if (gamepad && gamepad._isConnected) {
  60445. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  60446. }
  60447. }
  60448. });
  60449. this._onGamepadConnectedEvent = function (evt) {
  60450. var gamepad = evt.gamepad;
  60451. if (gamepad.index in _this._babylonGamepads) {
  60452. if (_this._babylonGamepads[gamepad.index].isConnected) {
  60453. return;
  60454. }
  60455. }
  60456. var newGamepad;
  60457. if (_this._babylonGamepads[gamepad.index]) {
  60458. newGamepad = _this._babylonGamepads[gamepad.index];
  60459. newGamepad.browserGamepad = gamepad;
  60460. newGamepad._isConnected = true;
  60461. }
  60462. else {
  60463. newGamepad = _this._addNewGamepad(gamepad);
  60464. }
  60465. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60466. _this._startMonitoringGamepads();
  60467. };
  60468. this._onGamepadDisconnectedEvent = function (evt) {
  60469. var gamepad = evt.gamepad;
  60470. // Remove the gamepad from the list of gamepads to monitor.
  60471. for (var i in _this._babylonGamepads) {
  60472. if (_this._babylonGamepads[i].index === gamepad.index) {
  60473. var disconnectedGamepad = _this._babylonGamepads[i];
  60474. disconnectedGamepad._isConnected = false;
  60475. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  60476. break;
  60477. }
  60478. }
  60479. };
  60480. if (this._gamepadSupport) {
  60481. //first add already-connected gamepads
  60482. this._updateGamepadObjects();
  60483. if (this._babylonGamepads.length) {
  60484. this._startMonitoringGamepads();
  60485. }
  60486. // Checking if the gamepad connected event is supported (like in Firefox)
  60487. if (this._gamepadEventSupported) {
  60488. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  60489. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  60490. }
  60491. else {
  60492. this._startMonitoringGamepads();
  60493. }
  60494. }
  60495. }
  60496. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  60497. get: function () {
  60498. return this._babylonGamepads;
  60499. },
  60500. enumerable: true,
  60501. configurable: true
  60502. });
  60503. GamepadManager.prototype.getGamepadByType = function (type) {
  60504. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  60505. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  60506. var gamepad = _a[_i];
  60507. if (gamepad && gamepad.type === type) {
  60508. return gamepad;
  60509. }
  60510. }
  60511. return null;
  60512. };
  60513. GamepadManager.prototype.dispose = function () {
  60514. if (this._gamepadEventSupported) {
  60515. if (this._onGamepadConnectedEvent) {
  60516. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  60517. }
  60518. if (this._onGamepadDisconnectedEvent) {
  60519. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  60520. }
  60521. this._onGamepadConnectedEvent = null;
  60522. this._onGamepadDisconnectedEvent = null;
  60523. }
  60524. this._babylonGamepads.forEach(function (gamepad) {
  60525. gamepad.dispose();
  60526. });
  60527. this.onGamepadConnectedObservable.clear();
  60528. this.onGamepadDisconnectedObservable.clear();
  60529. this._oneGamepadConnected = false;
  60530. this._stopMonitoringGamepads();
  60531. this._babylonGamepads = [];
  60532. };
  60533. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  60534. if (!this._oneGamepadConnected) {
  60535. this._oneGamepadConnected = true;
  60536. }
  60537. var newGamepad;
  60538. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  60539. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  60540. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  60541. }
  60542. else if (gamepad.pose) {
  60543. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  60544. }
  60545. else {
  60546. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  60547. }
  60548. this._babylonGamepads[newGamepad.index] = newGamepad;
  60549. return newGamepad;
  60550. };
  60551. GamepadManager.prototype._startMonitoringGamepads = function () {
  60552. if (!this._isMonitoring) {
  60553. this._isMonitoring = true;
  60554. //back-comp
  60555. if (!this._scene) {
  60556. this._checkGamepadsStatus();
  60557. }
  60558. }
  60559. };
  60560. GamepadManager.prototype._stopMonitoringGamepads = function () {
  60561. this._isMonitoring = false;
  60562. };
  60563. GamepadManager.prototype._checkGamepadsStatus = function () {
  60564. var _this = this;
  60565. // Hack to be compatible Chrome
  60566. this._updateGamepadObjects();
  60567. for (var i in this._babylonGamepads) {
  60568. var gamepad = this._babylonGamepads[i];
  60569. if (!gamepad || !gamepad.isConnected) {
  60570. continue;
  60571. }
  60572. gamepad.update();
  60573. }
  60574. if (this._isMonitoring && !this._scene) {
  60575. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  60576. }
  60577. };
  60578. // This function is called only on Chrome, which does not properly support
  60579. // connection/disconnection events and forces you to recopy again the gamepad object
  60580. GamepadManager.prototype._updateGamepadObjects = function () {
  60581. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  60582. for (var i = 0; i < gamepads.length; i++) {
  60583. if (gamepads[i]) {
  60584. if (!this._babylonGamepads[gamepads[i].index]) {
  60585. var newGamepad = this._addNewGamepad(gamepads[i]);
  60586. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60587. }
  60588. else {
  60589. // Forced to copy again this object for Chrome for unknown reason
  60590. this._babylonGamepads[i].browserGamepad = gamepads[i];
  60591. if (!this._babylonGamepads[i].isConnected) {
  60592. this._babylonGamepads[i]._isConnected = true;
  60593. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  60594. }
  60595. }
  60596. }
  60597. }
  60598. };
  60599. return GamepadManager;
  60600. }());
  60601. BABYLON.GamepadManager = GamepadManager;
  60602. })(BABYLON || (BABYLON = {}));
  60603. //# sourceMappingURL=babylon.gamepadManager.js.map
  60604. var BABYLON;
  60605. (function (BABYLON) {
  60606. var StickValues = /** @class */ (function () {
  60607. function StickValues(x, y) {
  60608. this.x = x;
  60609. this.y = y;
  60610. }
  60611. return StickValues;
  60612. }());
  60613. BABYLON.StickValues = StickValues;
  60614. var Gamepad = /** @class */ (function () {
  60615. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  60616. if (leftStickX === void 0) { leftStickX = 0; }
  60617. if (leftStickY === void 0) { leftStickY = 1; }
  60618. if (rightStickX === void 0) { rightStickX = 2; }
  60619. if (rightStickY === void 0) { rightStickY = 3; }
  60620. this.id = id;
  60621. this.index = index;
  60622. this.browserGamepad = browserGamepad;
  60623. this._isConnected = true;
  60624. this._invertLeftStickY = false;
  60625. this.type = Gamepad.GAMEPAD;
  60626. this._leftStickAxisX = leftStickX;
  60627. this._leftStickAxisY = leftStickY;
  60628. this._rightStickAxisX = rightStickX;
  60629. this._rightStickAxisY = rightStickY;
  60630. if (this.browserGamepad.axes.length >= 2) {
  60631. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60632. }
  60633. if (this.browserGamepad.axes.length >= 4) {
  60634. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60635. }
  60636. }
  60637. Object.defineProperty(Gamepad.prototype, "isConnected", {
  60638. get: function () {
  60639. return this._isConnected;
  60640. },
  60641. enumerable: true,
  60642. configurable: true
  60643. });
  60644. Gamepad.prototype.onleftstickchanged = function (callback) {
  60645. this._onleftstickchanged = callback;
  60646. };
  60647. Gamepad.prototype.onrightstickchanged = function (callback) {
  60648. this._onrightstickchanged = callback;
  60649. };
  60650. Object.defineProperty(Gamepad.prototype, "leftStick", {
  60651. get: function () {
  60652. return this._leftStick;
  60653. },
  60654. set: function (newValues) {
  60655. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  60656. this._onleftstickchanged(newValues);
  60657. }
  60658. this._leftStick = newValues;
  60659. },
  60660. enumerable: true,
  60661. configurable: true
  60662. });
  60663. Object.defineProperty(Gamepad.prototype, "rightStick", {
  60664. get: function () {
  60665. return this._rightStick;
  60666. },
  60667. set: function (newValues) {
  60668. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  60669. this._onrightstickchanged(newValues);
  60670. }
  60671. this._rightStick = newValues;
  60672. },
  60673. enumerable: true,
  60674. configurable: true
  60675. });
  60676. Gamepad.prototype.update = function () {
  60677. if (this._leftStick) {
  60678. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60679. if (this._invertLeftStickY) {
  60680. this.leftStick.y *= -1;
  60681. }
  60682. }
  60683. if (this._rightStick) {
  60684. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60685. }
  60686. };
  60687. Gamepad.prototype.dispose = function () {
  60688. };
  60689. Gamepad.GAMEPAD = 0;
  60690. Gamepad.GENERIC = 1;
  60691. Gamepad.XBOX = 2;
  60692. Gamepad.POSE_ENABLED = 3;
  60693. return Gamepad;
  60694. }());
  60695. BABYLON.Gamepad = Gamepad;
  60696. var GenericPad = /** @class */ (function (_super) {
  60697. __extends(GenericPad, _super);
  60698. function GenericPad(id, index, browserGamepad) {
  60699. var _this = _super.call(this, id, index, browserGamepad) || this;
  60700. _this.onButtonDownObservable = new BABYLON.Observable();
  60701. _this.onButtonUpObservable = new BABYLON.Observable();
  60702. _this.type = Gamepad.GENERIC;
  60703. _this._buttons = new Array(browserGamepad.buttons.length);
  60704. return _this;
  60705. }
  60706. GenericPad.prototype.onbuttondown = function (callback) {
  60707. this._onbuttondown = callback;
  60708. };
  60709. GenericPad.prototype.onbuttonup = function (callback) {
  60710. this._onbuttonup = callback;
  60711. };
  60712. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  60713. if (newValue !== currentValue) {
  60714. if (newValue === 1) {
  60715. if (this._onbuttondown) {
  60716. this._onbuttondown(buttonIndex);
  60717. }
  60718. this.onButtonDownObservable.notifyObservers(buttonIndex);
  60719. }
  60720. if (newValue === 0) {
  60721. if (this._onbuttonup) {
  60722. this._onbuttonup(buttonIndex);
  60723. }
  60724. this.onButtonUpObservable.notifyObservers(buttonIndex);
  60725. }
  60726. }
  60727. return newValue;
  60728. };
  60729. GenericPad.prototype.update = function () {
  60730. _super.prototype.update.call(this);
  60731. for (var index = 0; index < this._buttons.length; index++) {
  60732. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  60733. }
  60734. };
  60735. GenericPad.prototype.dispose = function () {
  60736. _super.prototype.dispose.call(this);
  60737. this.onButtonDownObservable.clear();
  60738. this.onButtonUpObservable.clear();
  60739. };
  60740. return GenericPad;
  60741. }(Gamepad));
  60742. BABYLON.GenericPad = GenericPad;
  60743. })(BABYLON || (BABYLON = {}));
  60744. //# sourceMappingURL=babylon.gamepad.js.map
  60745. var BABYLON;
  60746. (function (BABYLON) {
  60747. var Xbox360Button;
  60748. (function (Xbox360Button) {
  60749. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  60750. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  60751. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  60752. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  60753. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  60754. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  60755. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  60756. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  60757. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  60758. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  60759. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  60760. var Xbox360Dpad;
  60761. (function (Xbox360Dpad) {
  60762. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  60763. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  60764. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  60765. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  60766. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  60767. var Xbox360Pad = /** @class */ (function (_super) {
  60768. __extends(Xbox360Pad, _super);
  60769. function Xbox360Pad(id, index, gamepad, xboxOne) {
  60770. if (xboxOne === void 0) { xboxOne = false; }
  60771. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  60772. _this._leftTrigger = 0;
  60773. _this._rightTrigger = 0;
  60774. _this.onButtonDownObservable = new BABYLON.Observable();
  60775. _this.onButtonUpObservable = new BABYLON.Observable();
  60776. _this.onPadDownObservable = new BABYLON.Observable();
  60777. _this.onPadUpObservable = new BABYLON.Observable();
  60778. _this._buttonA = 0;
  60779. _this._buttonB = 0;
  60780. _this._buttonX = 0;
  60781. _this._buttonY = 0;
  60782. _this._buttonBack = 0;
  60783. _this._buttonStart = 0;
  60784. _this._buttonLB = 0;
  60785. _this._buttonRB = 0;
  60786. _this._buttonLeftStick = 0;
  60787. _this._buttonRightStick = 0;
  60788. _this._dPadUp = 0;
  60789. _this._dPadDown = 0;
  60790. _this._dPadLeft = 0;
  60791. _this._dPadRight = 0;
  60792. _this._isXboxOnePad = false;
  60793. _this.type = BABYLON.Gamepad.XBOX;
  60794. _this._isXboxOnePad = xboxOne;
  60795. return _this;
  60796. }
  60797. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  60798. this._onlefttriggerchanged = callback;
  60799. };
  60800. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  60801. this._onrighttriggerchanged = callback;
  60802. };
  60803. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  60804. get: function () {
  60805. return this._leftTrigger;
  60806. },
  60807. set: function (newValue) {
  60808. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  60809. this._onlefttriggerchanged(newValue);
  60810. }
  60811. this._leftTrigger = newValue;
  60812. },
  60813. enumerable: true,
  60814. configurable: true
  60815. });
  60816. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  60817. get: function () {
  60818. return this._rightTrigger;
  60819. },
  60820. set: function (newValue) {
  60821. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  60822. this._onrighttriggerchanged(newValue);
  60823. }
  60824. this._rightTrigger = newValue;
  60825. },
  60826. enumerable: true,
  60827. configurable: true
  60828. });
  60829. Xbox360Pad.prototype.onbuttondown = function (callback) {
  60830. this._onbuttondown = callback;
  60831. };
  60832. Xbox360Pad.prototype.onbuttonup = function (callback) {
  60833. this._onbuttonup = callback;
  60834. };
  60835. Xbox360Pad.prototype.ondpaddown = function (callback) {
  60836. this._ondpaddown = callback;
  60837. };
  60838. Xbox360Pad.prototype.ondpadup = function (callback) {
  60839. this._ondpadup = callback;
  60840. };
  60841. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  60842. if (newValue !== currentValue) {
  60843. if (newValue === 1) {
  60844. if (this._onbuttondown) {
  60845. this._onbuttondown(buttonType);
  60846. }
  60847. this.onButtonDownObservable.notifyObservers(buttonType);
  60848. }
  60849. if (newValue === 0) {
  60850. if (this._onbuttonup) {
  60851. this._onbuttonup(buttonType);
  60852. }
  60853. this.onButtonUpObservable.notifyObservers(buttonType);
  60854. }
  60855. }
  60856. return newValue;
  60857. };
  60858. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  60859. if (newValue !== currentValue) {
  60860. if (newValue === 1) {
  60861. if (this._ondpaddown) {
  60862. this._ondpaddown(buttonType);
  60863. }
  60864. this.onPadDownObservable.notifyObservers(buttonType);
  60865. }
  60866. if (newValue === 0) {
  60867. if (this._ondpadup) {
  60868. this._ondpadup(buttonType);
  60869. }
  60870. this.onPadUpObservable.notifyObservers(buttonType);
  60871. }
  60872. }
  60873. return newValue;
  60874. };
  60875. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  60876. get: function () {
  60877. return this._buttonA;
  60878. },
  60879. set: function (value) {
  60880. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  60881. },
  60882. enumerable: true,
  60883. configurable: true
  60884. });
  60885. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  60886. get: function () {
  60887. return this._buttonB;
  60888. },
  60889. set: function (value) {
  60890. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  60891. },
  60892. enumerable: true,
  60893. configurable: true
  60894. });
  60895. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  60896. get: function () {
  60897. return this._buttonX;
  60898. },
  60899. set: function (value) {
  60900. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  60901. },
  60902. enumerable: true,
  60903. configurable: true
  60904. });
  60905. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  60906. get: function () {
  60907. return this._buttonY;
  60908. },
  60909. set: function (value) {
  60910. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  60911. },
  60912. enumerable: true,
  60913. configurable: true
  60914. });
  60915. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  60916. get: function () {
  60917. return this._buttonStart;
  60918. },
  60919. set: function (value) {
  60920. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  60921. },
  60922. enumerable: true,
  60923. configurable: true
  60924. });
  60925. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  60926. get: function () {
  60927. return this._buttonBack;
  60928. },
  60929. set: function (value) {
  60930. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  60931. },
  60932. enumerable: true,
  60933. configurable: true
  60934. });
  60935. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  60936. get: function () {
  60937. return this._buttonLB;
  60938. },
  60939. set: function (value) {
  60940. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  60941. },
  60942. enumerable: true,
  60943. configurable: true
  60944. });
  60945. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  60946. get: function () {
  60947. return this._buttonRB;
  60948. },
  60949. set: function (value) {
  60950. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  60951. },
  60952. enumerable: true,
  60953. configurable: true
  60954. });
  60955. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  60956. get: function () {
  60957. return this._buttonLeftStick;
  60958. },
  60959. set: function (value) {
  60960. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  60961. },
  60962. enumerable: true,
  60963. configurable: true
  60964. });
  60965. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  60966. get: function () {
  60967. return this._buttonRightStick;
  60968. },
  60969. set: function (value) {
  60970. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  60971. },
  60972. enumerable: true,
  60973. configurable: true
  60974. });
  60975. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  60976. get: function () {
  60977. return this._dPadUp;
  60978. },
  60979. set: function (value) {
  60980. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  60981. },
  60982. enumerable: true,
  60983. configurable: true
  60984. });
  60985. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  60986. get: function () {
  60987. return this._dPadDown;
  60988. },
  60989. set: function (value) {
  60990. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  60991. },
  60992. enumerable: true,
  60993. configurable: true
  60994. });
  60995. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  60996. get: function () {
  60997. return this._dPadLeft;
  60998. },
  60999. set: function (value) {
  61000. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  61001. },
  61002. enumerable: true,
  61003. configurable: true
  61004. });
  61005. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  61006. get: function () {
  61007. return this._dPadRight;
  61008. },
  61009. set: function (value) {
  61010. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  61011. },
  61012. enumerable: true,
  61013. configurable: true
  61014. });
  61015. Xbox360Pad.prototype.update = function () {
  61016. _super.prototype.update.call(this);
  61017. if (this._isXboxOnePad) {
  61018. this.buttonA = this.browserGamepad.buttons[0].value;
  61019. this.buttonB = this.browserGamepad.buttons[1].value;
  61020. this.buttonX = this.browserGamepad.buttons[2].value;
  61021. this.buttonY = this.browserGamepad.buttons[3].value;
  61022. this.buttonLB = this.browserGamepad.buttons[4].value;
  61023. this.buttonRB = this.browserGamepad.buttons[5].value;
  61024. this.leftTrigger = this.browserGamepad.axes[2];
  61025. this.rightTrigger = this.browserGamepad.axes[5];
  61026. this.buttonBack = this.browserGamepad.buttons[9].value;
  61027. this.buttonStart = this.browserGamepad.buttons[8].value;
  61028. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  61029. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  61030. this.dPadUp = this.browserGamepad.buttons[11].value;
  61031. this.dPadDown = this.browserGamepad.buttons[12].value;
  61032. this.dPadLeft = this.browserGamepad.buttons[13].value;
  61033. this.dPadRight = this.browserGamepad.buttons[14].value;
  61034. }
  61035. else {
  61036. this.buttonA = this.browserGamepad.buttons[0].value;
  61037. this.buttonB = this.browserGamepad.buttons[1].value;
  61038. this.buttonX = this.browserGamepad.buttons[2].value;
  61039. this.buttonY = this.browserGamepad.buttons[3].value;
  61040. this.buttonLB = this.browserGamepad.buttons[4].value;
  61041. this.buttonRB = this.browserGamepad.buttons[5].value;
  61042. this.leftTrigger = this.browserGamepad.buttons[6].value;
  61043. this.rightTrigger = this.browserGamepad.buttons[7].value;
  61044. this.buttonBack = this.browserGamepad.buttons[8].value;
  61045. this.buttonStart = this.browserGamepad.buttons[9].value;
  61046. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  61047. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  61048. this.dPadUp = this.browserGamepad.buttons[12].value;
  61049. this.dPadDown = this.browserGamepad.buttons[13].value;
  61050. this.dPadLeft = this.browserGamepad.buttons[14].value;
  61051. this.dPadRight = this.browserGamepad.buttons[15].value;
  61052. }
  61053. };
  61054. Xbox360Pad.prototype.dispose = function () {
  61055. _super.prototype.dispose.call(this);
  61056. this.onButtonDownObservable.clear();
  61057. this.onButtonUpObservable.clear();
  61058. this.onPadDownObservable.clear();
  61059. this.onPadUpObservable.clear();
  61060. };
  61061. return Xbox360Pad;
  61062. }(BABYLON.Gamepad));
  61063. BABYLON.Xbox360Pad = Xbox360Pad;
  61064. })(BABYLON || (BABYLON = {}));
  61065. //# sourceMappingURL=babylon.xboxGamepad.js.map
  61066. var BABYLON;
  61067. (function (BABYLON) {
  61068. var PoseEnabledControllerType;
  61069. (function (PoseEnabledControllerType) {
  61070. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  61071. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  61072. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  61073. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  61074. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  61075. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  61076. var PoseEnabledControllerHelper = /** @class */ (function () {
  61077. function PoseEnabledControllerHelper() {
  61078. }
  61079. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  61080. // Oculus Touch
  61081. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  61082. return new BABYLON.OculusTouchController(vrGamepad);
  61083. }
  61084. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  61085. return new BABYLON.WindowsMotionController(vrGamepad);
  61086. }
  61087. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  61088. return new BABYLON.ViveController(vrGamepad);
  61089. }
  61090. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  61091. return new BABYLON.GearVRController(vrGamepad);
  61092. }
  61093. else {
  61094. return new BABYLON.GenericController(vrGamepad);
  61095. }
  61096. };
  61097. return PoseEnabledControllerHelper;
  61098. }());
  61099. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  61100. var PoseEnabledController = /** @class */ (function (_super) {
  61101. __extends(PoseEnabledController, _super);
  61102. function PoseEnabledController(browserGamepad) {
  61103. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  61104. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  61105. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  61106. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  61107. // Represents device position and rotation in babylon space
  61108. _this.devicePosition = BABYLON.Vector3.Zero();
  61109. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61110. _this.deviceScaleFactor = 1;
  61111. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  61112. _this._deviceToWorld = BABYLON.Matrix.Identity();
  61113. _this._workingMatrix = BABYLON.Matrix.Identity();
  61114. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  61115. _this.controllerType = PoseEnabledControllerType.GENERIC;
  61116. _this.position = BABYLON.Vector3.Zero();
  61117. _this.rotationQuaternion = new BABYLON.Quaternion();
  61118. _this._calculatedPosition = BABYLON.Vector3.Zero();
  61119. _this._calculatedRotation = new BABYLON.Quaternion();
  61120. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  61121. return _this;
  61122. }
  61123. PoseEnabledController.prototype.update = function () {
  61124. _super.prototype.update.call(this);
  61125. var pose = this.browserGamepad.pose;
  61126. this.updateFromDevice(pose);
  61127. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  61128. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  61129. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  61130. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  61131. if (this._mesh) {
  61132. this._mesh.position.copyFrom(this.devicePosition);
  61133. if (this._mesh.rotationQuaternion) {
  61134. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61135. }
  61136. }
  61137. };
  61138. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  61139. if (poseData) {
  61140. this.rawPose = poseData;
  61141. if (poseData.position) {
  61142. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  61143. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  61144. this._deviceRoomPosition.z *= -1;
  61145. }
  61146. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  61147. this._calculatedPosition.addInPlace(this.position);
  61148. }
  61149. var pose = this.rawPose;
  61150. if (poseData.orientation && pose.orientation) {
  61151. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  61152. if (this._mesh) {
  61153. if (this._mesh.getScene().useRightHandedSystem) {
  61154. this._deviceRoomRotationQuaternion.z *= -1;
  61155. this._deviceRoomRotationQuaternion.w *= -1;
  61156. }
  61157. else {
  61158. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  61159. }
  61160. }
  61161. // if the camera is set, rotate to the camera's rotation
  61162. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  61163. }
  61164. }
  61165. };
  61166. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  61167. if (this._mesh) {
  61168. this._mesh.parent = null;
  61169. }
  61170. this._mesh = mesh;
  61171. if (this._poseControlledCamera) {
  61172. this._mesh.parent = this._poseControlledCamera;
  61173. }
  61174. if (!this._mesh.rotationQuaternion) {
  61175. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  61176. }
  61177. };
  61178. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  61179. this._poseControlledCamera = camera;
  61180. if (this._mesh) {
  61181. this._mesh.parent = this._poseControlledCamera;
  61182. }
  61183. };
  61184. PoseEnabledController.prototype.dispose = function () {
  61185. if (this._mesh) {
  61186. this._mesh.dispose();
  61187. }
  61188. this._mesh = null;
  61189. _super.prototype.dispose.call(this);
  61190. };
  61191. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  61192. get: function () {
  61193. return this._mesh;
  61194. },
  61195. enumerable: true,
  61196. configurable: true
  61197. });
  61198. PoseEnabledController.prototype.getForwardRay = function (length) {
  61199. if (length === void 0) { length = 100; }
  61200. if (!this.mesh) {
  61201. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  61202. }
  61203. var m = this.mesh.getWorldMatrix();
  61204. var origin = m.getTranslation();
  61205. var forward = new BABYLON.Vector3(0, 0, -1);
  61206. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61207. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61208. return new BABYLON.Ray(origin, direction, length);
  61209. };
  61210. return PoseEnabledController;
  61211. }(BABYLON.Gamepad));
  61212. BABYLON.PoseEnabledController = PoseEnabledController;
  61213. })(BABYLON || (BABYLON = {}));
  61214. //# sourceMappingURL=babylon.poseEnabledController.js.map
  61215. var BABYLON;
  61216. (function (BABYLON) {
  61217. var WebVRController = /** @class */ (function (_super) {
  61218. __extends(WebVRController, _super);
  61219. function WebVRController(vrGamepad) {
  61220. var _this = _super.call(this, vrGamepad) || this;
  61221. // Observables
  61222. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  61223. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  61224. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  61225. _this.onPadStateChangedObservable = new BABYLON.Observable();
  61226. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  61227. _this.pad = { x: 0, y: 0 };
  61228. // avoid GC, store state in a tmp object
  61229. _this._changes = {
  61230. pressChanged: false,
  61231. touchChanged: false,
  61232. valueChanged: false,
  61233. changed: false
  61234. };
  61235. _this._buttons = new Array(vrGamepad.buttons.length);
  61236. _this.hand = vrGamepad.hand;
  61237. return _this;
  61238. }
  61239. WebVRController.prototype.onButtonStateChange = function (callback) {
  61240. this._onButtonStateChange = callback;
  61241. };
  61242. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  61243. get: function () {
  61244. return this._defaultModel;
  61245. },
  61246. enumerable: true,
  61247. configurable: true
  61248. });
  61249. WebVRController.prototype.update = function () {
  61250. _super.prototype.update.call(this);
  61251. for (var index = 0; index < this._buttons.length; index++) {
  61252. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  61253. }
  61254. ;
  61255. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  61256. this.pad.x = this.leftStick.x;
  61257. this.pad.y = this.leftStick.y;
  61258. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  61259. }
  61260. };
  61261. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  61262. if (!newState) {
  61263. newState = {
  61264. pressed: false,
  61265. touched: false,
  61266. value: 0
  61267. };
  61268. }
  61269. if (!currentState) {
  61270. this._buttons[buttonIndex] = {
  61271. pressed: newState.pressed,
  61272. touched: newState.touched,
  61273. value: newState.value
  61274. };
  61275. return;
  61276. }
  61277. this._checkChanges(newState, currentState);
  61278. if (this._changes.changed) {
  61279. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  61280. this.handleButtonChange(buttonIndex, newState, this._changes);
  61281. }
  61282. this._buttons[buttonIndex].pressed = newState.pressed;
  61283. this._buttons[buttonIndex].touched = newState.touched;
  61284. // oculus triggers are never 0, thou not touched.
  61285. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  61286. };
  61287. WebVRController.prototype._checkChanges = function (newState, currentState) {
  61288. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  61289. this._changes.touchChanged = newState.touched !== currentState.touched;
  61290. this._changes.valueChanged = newState.value !== currentState.value;
  61291. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  61292. return this._changes;
  61293. };
  61294. WebVRController.prototype.dispose = function () {
  61295. _super.prototype.dispose.call(this);
  61296. this.onTriggerStateChangedObservable.clear();
  61297. this.onMainButtonStateChangedObservable.clear();
  61298. this.onSecondaryButtonStateChangedObservable.clear();
  61299. this.onPadStateChangedObservable.clear();
  61300. this.onPadValuesChangedObservable.clear();
  61301. };
  61302. return WebVRController;
  61303. }(BABYLON.PoseEnabledController));
  61304. BABYLON.WebVRController = WebVRController;
  61305. })(BABYLON || (BABYLON = {}));
  61306. //# sourceMappingURL=babylon.webVRController.js.map
  61307. var BABYLON;
  61308. (function (BABYLON) {
  61309. var OculusTouchController = /** @class */ (function (_super) {
  61310. __extends(OculusTouchController, _super);
  61311. function OculusTouchController(vrGamepad) {
  61312. var _this = _super.call(this, vrGamepad) || this;
  61313. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  61314. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  61315. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  61316. return _this;
  61317. }
  61318. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61319. var _this = this;
  61320. var meshName;
  61321. // Hand
  61322. if (this.hand === 'left') {
  61323. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  61324. }
  61325. else {
  61326. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  61327. }
  61328. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  61329. /*
  61330. Parent Mesh name: oculus_touch_left
  61331. - body
  61332. - trigger
  61333. - thumbstick
  61334. - grip
  61335. - button_y
  61336. - button_x
  61337. - button_enter
  61338. */
  61339. _this._defaultModel = newMeshes[1];
  61340. _this.attachToMesh(_this._defaultModel);
  61341. if (meshLoaded) {
  61342. meshLoaded(_this._defaultModel);
  61343. }
  61344. });
  61345. };
  61346. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  61347. // helper getters for left and right hand.
  61348. get: function () {
  61349. if (this.hand === 'right') {
  61350. return this.onMainButtonStateChangedObservable;
  61351. }
  61352. else {
  61353. throw new Error('No A button on left hand');
  61354. }
  61355. },
  61356. enumerable: true,
  61357. configurable: true
  61358. });
  61359. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  61360. get: function () {
  61361. if (this.hand === 'right') {
  61362. return this.onSecondaryButtonStateChangedObservable;
  61363. }
  61364. else {
  61365. throw new Error('No B button on left hand');
  61366. }
  61367. },
  61368. enumerable: true,
  61369. configurable: true
  61370. });
  61371. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  61372. get: function () {
  61373. if (this.hand === 'left') {
  61374. return this.onMainButtonStateChangedObservable;
  61375. }
  61376. else {
  61377. throw new Error('No X button on right hand');
  61378. }
  61379. },
  61380. enumerable: true,
  61381. configurable: true
  61382. });
  61383. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  61384. get: function () {
  61385. if (this.hand === 'left') {
  61386. return this.onSecondaryButtonStateChangedObservable;
  61387. }
  61388. else {
  61389. throw new Error('No Y button on right hand');
  61390. }
  61391. },
  61392. enumerable: true,
  61393. configurable: true
  61394. });
  61395. /*
  61396. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  61397. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  61398. 2) secondary trigger (same)
  61399. 3) A (right) X (left), touch, pressed = value
  61400. 4) B / Y
  61401. 5) thumb rest
  61402. */
  61403. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61404. var notifyObject = state; //{ state: state, changes: changes };
  61405. var triggerDirection = this.hand === 'right' ? -1 : 1;
  61406. switch (buttonIdx) {
  61407. case 0:
  61408. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61409. return;
  61410. case 1:// index trigger
  61411. if (this._defaultModel) {
  61412. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  61413. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  61414. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  61415. }
  61416. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61417. return;
  61418. case 2:// secondary trigger
  61419. if (this._defaultModel) {
  61420. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  61421. }
  61422. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  61423. return;
  61424. case 3:
  61425. if (this._defaultModel) {
  61426. if (notifyObject.pressed) {
  61427. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  61428. }
  61429. else {
  61430. (this._defaultModel.getChildren()[1]).position.y = 0;
  61431. }
  61432. }
  61433. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61434. return;
  61435. case 4:
  61436. if (this._defaultModel) {
  61437. if (notifyObject.pressed) {
  61438. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61439. }
  61440. else {
  61441. (this._defaultModel.getChildren()[2]).position.y = 0;
  61442. }
  61443. }
  61444. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61445. return;
  61446. case 5:
  61447. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  61448. return;
  61449. }
  61450. };
  61451. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  61452. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  61453. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  61454. return OculusTouchController;
  61455. }(BABYLON.WebVRController));
  61456. BABYLON.OculusTouchController = OculusTouchController;
  61457. })(BABYLON || (BABYLON = {}));
  61458. //# sourceMappingURL=babylon.oculusTouchController.js.map
  61459. var BABYLON;
  61460. (function (BABYLON) {
  61461. var ViveController = /** @class */ (function (_super) {
  61462. __extends(ViveController, _super);
  61463. function ViveController(vrGamepad) {
  61464. var _this = _super.call(this, vrGamepad) || this;
  61465. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  61466. _this._invertLeftStickY = true;
  61467. return _this;
  61468. }
  61469. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61470. var _this = this;
  61471. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  61472. /*
  61473. Parent Mesh name: ViveWand
  61474. - body
  61475. - r_gripper
  61476. - l_gripper
  61477. - menu_button
  61478. - system_button
  61479. - trackpad
  61480. - trigger
  61481. - LED
  61482. */
  61483. _this._defaultModel = newMeshes[1];
  61484. _this.attachToMesh(_this._defaultModel);
  61485. if (meshLoaded) {
  61486. meshLoaded(_this._defaultModel);
  61487. }
  61488. });
  61489. };
  61490. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  61491. get: function () {
  61492. return this.onMainButtonStateChangedObservable;
  61493. },
  61494. enumerable: true,
  61495. configurable: true
  61496. });
  61497. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  61498. get: function () {
  61499. return this.onMainButtonStateChangedObservable;
  61500. },
  61501. enumerable: true,
  61502. configurable: true
  61503. });
  61504. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  61505. get: function () {
  61506. return this.onSecondaryButtonStateChangedObservable;
  61507. },
  61508. enumerable: true,
  61509. configurable: true
  61510. });
  61511. /**
  61512. * Vive mapping:
  61513. * 0: touchpad
  61514. * 1: trigger
  61515. * 2: left AND right buttons
  61516. * 3: menu button
  61517. */
  61518. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61519. var notifyObject = state; //{ state: state, changes: changes };
  61520. switch (buttonIdx) {
  61521. case 0:
  61522. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61523. return;
  61524. case 1:// index trigger
  61525. if (this._defaultModel) {
  61526. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  61527. }
  61528. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61529. return;
  61530. case 2:// left AND right button
  61531. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61532. return;
  61533. case 3:
  61534. if (this._defaultModel) {
  61535. if (notifyObject.pressed) {
  61536. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61537. }
  61538. else {
  61539. (this._defaultModel.getChildren()[2]).position.y = 0;
  61540. }
  61541. }
  61542. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61543. return;
  61544. }
  61545. };
  61546. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  61547. ViveController.MODEL_FILENAME = 'wand.babylon';
  61548. return ViveController;
  61549. }(BABYLON.WebVRController));
  61550. BABYLON.ViveController = ViveController;
  61551. })(BABYLON || (BABYLON = {}));
  61552. //# sourceMappingURL=babylon.viveController.js.map
  61553. var BABYLON;
  61554. (function (BABYLON) {
  61555. var GenericController = /** @class */ (function (_super) {
  61556. __extends(GenericController, _super);
  61557. function GenericController(vrGamepad) {
  61558. return _super.call(this, vrGamepad) || this;
  61559. }
  61560. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61561. var _this = this;
  61562. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  61563. _this._defaultModel = newMeshes[1];
  61564. _this.attachToMesh(_this._defaultModel);
  61565. if (meshLoaded) {
  61566. meshLoaded(_this._defaultModel);
  61567. }
  61568. });
  61569. };
  61570. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61571. console.log("Button id: " + buttonIdx + "state: ");
  61572. console.dir(state);
  61573. };
  61574. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61575. GenericController.MODEL_FILENAME = 'generic.babylon';
  61576. return GenericController;
  61577. }(BABYLON.WebVRController));
  61578. BABYLON.GenericController = GenericController;
  61579. })(BABYLON || (BABYLON = {}));
  61580. //# sourceMappingURL=babylon.genericController.js.map
  61581. var BABYLON;
  61582. (function (BABYLON) {
  61583. var LoadedMeshInfo = /** @class */ (function () {
  61584. function LoadedMeshInfo() {
  61585. this.buttonMeshes = {};
  61586. this.axisMeshes = {};
  61587. }
  61588. return LoadedMeshInfo;
  61589. }());
  61590. var WindowsMotionController = /** @class */ (function (_super) {
  61591. __extends(WindowsMotionController, _super);
  61592. function WindowsMotionController(vrGamepad) {
  61593. var _this = _super.call(this, vrGamepad) || this;
  61594. _this._mapping = {
  61595. // Semantic button names
  61596. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  61597. // A mapping of the button name to glTF model node name
  61598. // that should be transformed by button value.
  61599. buttonMeshNames: {
  61600. 'trigger': 'SELECT',
  61601. 'menu': 'MENU',
  61602. 'grip': 'GRASP',
  61603. 'thumbstick': 'THUMBSTICK_PRESS',
  61604. 'trackpad': 'TOUCHPAD_PRESS'
  61605. },
  61606. // This mapping is used to translate from the Motion Controller to Babylon semantics
  61607. buttonObservableNames: {
  61608. 'trigger': 'onTriggerStateChangedObservable',
  61609. 'menu': 'onSecondaryButtonStateChangedObservable',
  61610. 'grip': 'onMainButtonStateChangedObservable',
  61611. 'thumbstick': 'onPadStateChangedObservable',
  61612. 'trackpad': 'onTrackpadChangedObservable'
  61613. },
  61614. // A mapping of the axis name to glTF model node name
  61615. // that should be transformed by axis value.
  61616. // This array mirrors the browserGamepad.axes array, such that
  61617. // the mesh corresponding to axis 0 is in this array index 0.
  61618. axisMeshNames: [
  61619. 'THUMBSTICK_X',
  61620. 'THUMBSTICK_Y',
  61621. 'TOUCHPAD_TOUCH_X',
  61622. 'TOUCHPAD_TOUCH_Y'
  61623. ],
  61624. pointingPoseMeshName: 'POINTING_POSE'
  61625. };
  61626. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  61627. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  61628. _this.trackpad = { x: 0, y: 0 };
  61629. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  61630. _this._loadedMeshInfo = null;
  61631. return _this;
  61632. }
  61633. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  61634. get: function () {
  61635. return this.onTriggerStateChangedObservable;
  61636. },
  61637. enumerable: true,
  61638. configurable: true
  61639. });
  61640. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  61641. get: function () {
  61642. return this.onSecondaryButtonStateChangedObservable;
  61643. },
  61644. enumerable: true,
  61645. configurable: true
  61646. });
  61647. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  61648. get: function () {
  61649. return this.onMainButtonStateChangedObservable;
  61650. },
  61651. enumerable: true,
  61652. configurable: true
  61653. });
  61654. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  61655. get: function () {
  61656. return this.onPadStateChangedObservable;
  61657. },
  61658. enumerable: true,
  61659. configurable: true
  61660. });
  61661. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  61662. get: function () {
  61663. return this.onTrackpadChangedObservable;
  61664. },
  61665. enumerable: true,
  61666. configurable: true
  61667. });
  61668. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  61669. get: function () {
  61670. return this.onTrackpadValuesChangedObservable;
  61671. },
  61672. enumerable: true,
  61673. configurable: true
  61674. });
  61675. /**
  61676. * Called once per frame by the engine.
  61677. */
  61678. WindowsMotionController.prototype.update = function () {
  61679. _super.prototype.update.call(this);
  61680. // Only need to animate axes if there is a loaded mesh
  61681. if (this._loadedMeshInfo) {
  61682. if (this.browserGamepad.axes) {
  61683. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  61684. this.trackpad.x = this.browserGamepad["axes"][2];
  61685. this.trackpad.y = this.browserGamepad["axes"][3];
  61686. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  61687. }
  61688. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  61689. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  61690. }
  61691. }
  61692. }
  61693. };
  61694. /**
  61695. * Called once for each button that changed state since the last frame
  61696. * @param buttonIdx Which button index changed
  61697. * @param state New state of the button
  61698. * @param changes Which properties on the state changed since last frame
  61699. */
  61700. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61701. var buttonName = this._mapping.buttons[buttonIdx];
  61702. if (!buttonName) {
  61703. return;
  61704. }
  61705. // Only emit events for buttons that we know how to map from index to name
  61706. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  61707. if (observable) {
  61708. observable.notifyObservers(state);
  61709. }
  61710. this.lerpButtonTransform(buttonName, state.value);
  61711. };
  61712. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  61713. // If there is no loaded mesh, there is nothing to transform.
  61714. if (!this._loadedMeshInfo) {
  61715. return;
  61716. }
  61717. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  61718. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61719. return;
  61720. }
  61721. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  61722. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  61723. };
  61724. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  61725. if (!this._loadedMeshInfo) {
  61726. return;
  61727. }
  61728. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  61729. if (!meshInfo) {
  61730. return;
  61731. }
  61732. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61733. return;
  61734. }
  61735. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  61736. var lerpValue = axisValue * 0.5 + 0.5;
  61737. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  61738. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  61739. };
  61740. /**
  61741. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  61742. * @param scene scene in which to add meshes
  61743. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  61744. */
  61745. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  61746. var _this = this;
  61747. if (forceDefault === void 0) { forceDefault = false; }
  61748. var path;
  61749. var filename;
  61750. // Checking if GLB loader is present
  61751. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  61752. // Determine the device specific folder based on the ID suffix
  61753. var device = 'default';
  61754. if (this.id && !forceDefault) {
  61755. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  61756. device = ((match && match[0]) || device);
  61757. }
  61758. // Hand
  61759. if (this.hand === 'left') {
  61760. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  61761. }
  61762. else {
  61763. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  61764. }
  61765. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  61766. }
  61767. else {
  61768. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  61769. path = BABYLON.GenericController.MODEL_BASE_URL;
  61770. filename = BABYLON.GenericController.MODEL_FILENAME;
  61771. }
  61772. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  61773. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  61774. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  61775. if (!_this._loadedMeshInfo) {
  61776. return;
  61777. }
  61778. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  61779. _this.attachToMesh(_this._defaultModel);
  61780. if (meshLoaded) {
  61781. meshLoaded(_this._defaultModel);
  61782. }
  61783. }, null, function (scene, message) {
  61784. BABYLON.Tools.Log(message);
  61785. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  61786. if (!forceDefault) {
  61787. _this.initControllerMesh(scene, meshLoaded, true);
  61788. }
  61789. });
  61790. };
  61791. /**
  61792. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  61793. * can be transformed by button presses and axes values, based on this._mapping.
  61794. *
  61795. * @param scene scene in which the meshes exist
  61796. * @param meshes list of meshes that make up the controller model to process
  61797. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  61798. */
  61799. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  61800. var loadedMeshInfo = null;
  61801. // Create a new mesh to contain the glTF hierarchy
  61802. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  61803. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  61804. var childMesh = null;
  61805. for (var i = 0; i < meshes.length; i++) {
  61806. var mesh = meshes[i];
  61807. if (!mesh.parent) {
  61808. // Exclude controller meshes from picking results
  61809. mesh.isPickable = false;
  61810. // Handle root node, attach to the new parentMesh
  61811. childMesh = mesh;
  61812. break;
  61813. }
  61814. }
  61815. if (childMesh) {
  61816. childMesh.setParent(parentMesh);
  61817. // Create our mesh info. Note that this method will always return non-null.
  61818. loadedMeshInfo = this.createMeshInfo(parentMesh);
  61819. }
  61820. else {
  61821. BABYLON.Tools.Warn('Could not find root node in model file.');
  61822. }
  61823. return loadedMeshInfo;
  61824. };
  61825. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  61826. var loadedMeshInfo = new LoadedMeshInfo();
  61827. var i;
  61828. loadedMeshInfo.rootNode = rootNode;
  61829. // Reset the caches
  61830. loadedMeshInfo.buttonMeshes = {};
  61831. loadedMeshInfo.axisMeshes = {};
  61832. // Button Meshes
  61833. for (i = 0; i < this._mapping.buttons.length; i++) {
  61834. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  61835. if (!buttonMeshName) {
  61836. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  61837. continue;
  61838. }
  61839. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  61840. if (!buttonMesh) {
  61841. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  61842. continue;
  61843. }
  61844. var buttonMeshInfo = {
  61845. index: i,
  61846. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  61847. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  61848. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  61849. };
  61850. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  61851. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  61852. }
  61853. else {
  61854. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  61855. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  61856. '(VALUE: ' + !!buttonMeshInfo.value +
  61857. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  61858. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  61859. ')');
  61860. }
  61861. }
  61862. // Axis Meshes
  61863. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  61864. var axisMeshName = this._mapping.axisMeshNames[i];
  61865. if (!axisMeshName) {
  61866. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  61867. continue;
  61868. }
  61869. var axisMesh = getChildByName(rootNode, axisMeshName);
  61870. if (!axisMesh) {
  61871. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  61872. continue;
  61873. }
  61874. var axisMeshInfo = {
  61875. index: i,
  61876. value: getImmediateChildByName(axisMesh, 'VALUE'),
  61877. min: getImmediateChildByName(axisMesh, 'MIN'),
  61878. max: getImmediateChildByName(axisMesh, 'MAX')
  61879. };
  61880. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  61881. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  61882. }
  61883. else {
  61884. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  61885. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  61886. '(VALUE: ' + !!axisMeshInfo.value +
  61887. ', MIN: ' + !!axisMeshInfo.min +
  61888. ', MAX:' + !!axisMeshInfo.max +
  61889. ')');
  61890. }
  61891. }
  61892. // Pointing Ray
  61893. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  61894. if (!loadedMeshInfo.pointingPoseNode) {
  61895. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  61896. }
  61897. return loadedMeshInfo;
  61898. // Look through all children recursively. This will return null if no mesh exists with the given name.
  61899. function getChildByName(node, name) {
  61900. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  61901. }
  61902. // Look through only immediate children. This will return null if no mesh exists with the given name.
  61903. function getImmediateChildByName(node, name) {
  61904. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  61905. }
  61906. };
  61907. WindowsMotionController.prototype.getForwardRay = function (length) {
  61908. if (length === void 0) { length = 100; }
  61909. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  61910. return _super.prototype.getForwardRay.call(this, length);
  61911. }
  61912. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  61913. var origin = m.getTranslation();
  61914. var forward = new BABYLON.Vector3(0, 0, -1);
  61915. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61916. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61917. return new BABYLON.Ray(origin, direction, length);
  61918. };
  61919. WindowsMotionController.prototype.dispose = function () {
  61920. _super.prototype.dispose.call(this);
  61921. this.onTrackpadChangedObservable.clear();
  61922. };
  61923. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  61924. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  61925. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  61926. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  61927. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  61928. return WindowsMotionController;
  61929. }(BABYLON.WebVRController));
  61930. BABYLON.WindowsMotionController = WindowsMotionController;
  61931. })(BABYLON || (BABYLON = {}));
  61932. //# sourceMappingURL=babylon.windowsMotionController.js.map
  61933. var BABYLON;
  61934. (function (BABYLON) {
  61935. var GearVRController = /** @class */ (function (_super) {
  61936. __extends(GearVRController, _super);
  61937. function GearVRController(vrGamepad) {
  61938. var _this = _super.call(this, vrGamepad) || this;
  61939. _this._buttonIndexToObservableNameMap = [
  61940. 'onTrackpadChangedObservable',
  61941. 'onTriggerStateChangedObservable' // Trigger
  61942. ];
  61943. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  61944. return _this;
  61945. }
  61946. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61947. var _this = this;
  61948. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  61949. _this._defaultModel = newMeshes[1];
  61950. _this.attachToMesh(_this._defaultModel);
  61951. if (meshLoaded) {
  61952. meshLoaded(_this._defaultModel);
  61953. }
  61954. });
  61955. };
  61956. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61957. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  61958. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  61959. // Only emit events for buttons that we know how to map from index to observable
  61960. var observable = this[observableName];
  61961. if (observable) {
  61962. observable.notifyObservers(state);
  61963. }
  61964. }
  61965. };
  61966. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61967. GearVRController.MODEL_FILENAME = 'generic.babylon';
  61968. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  61969. return GearVRController;
  61970. }(BABYLON.WebVRController));
  61971. BABYLON.GearVRController = GearVRController;
  61972. })(BABYLON || (BABYLON = {}));
  61973. //# sourceMappingURL=babylon.gearVRController.js.map
  61974. var BABYLON;
  61975. (function (BABYLON) {
  61976. var FollowCamera = /** @class */ (function (_super) {
  61977. __extends(FollowCamera, _super);
  61978. function FollowCamera(name, position, scene, lockedTarget) {
  61979. if (lockedTarget === void 0) { lockedTarget = null; }
  61980. var _this = _super.call(this, name, position, scene) || this;
  61981. _this.radius = 12;
  61982. _this.rotationOffset = 0;
  61983. _this.heightOffset = 4;
  61984. _this.cameraAcceleration = 0.05;
  61985. _this.maxCameraSpeed = 20;
  61986. _this.lockedTarget = lockedTarget;
  61987. return _this;
  61988. }
  61989. FollowCamera.prototype.getRadians = function (degrees) {
  61990. return degrees * Math.PI / 180;
  61991. };
  61992. FollowCamera.prototype.follow = function (cameraTarget) {
  61993. if (!cameraTarget)
  61994. return;
  61995. var yRotation;
  61996. if (cameraTarget.rotationQuaternion) {
  61997. var rotMatrix = new BABYLON.Matrix();
  61998. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  61999. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  62000. }
  62001. else {
  62002. yRotation = cameraTarget.rotation.y;
  62003. }
  62004. var radians = this.getRadians(this.rotationOffset) + yRotation;
  62005. var targetPosition = cameraTarget.getAbsolutePosition();
  62006. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  62007. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  62008. var dx = targetX - this.position.x;
  62009. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  62010. var dz = (targetZ) - this.position.z;
  62011. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  62012. var vy = dy * this.cameraAcceleration;
  62013. var vz = dz * this.cameraAcceleration * 2;
  62014. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  62015. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62016. }
  62017. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  62018. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62019. }
  62020. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  62021. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62022. }
  62023. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  62024. this.setTarget(targetPosition);
  62025. };
  62026. FollowCamera.prototype._checkInputs = function () {
  62027. _super.prototype._checkInputs.call(this);
  62028. if (this.lockedTarget) {
  62029. this.follow(this.lockedTarget);
  62030. }
  62031. };
  62032. FollowCamera.prototype.getClassName = function () {
  62033. return "FollowCamera";
  62034. };
  62035. __decorate([
  62036. BABYLON.serialize()
  62037. ], FollowCamera.prototype, "radius", void 0);
  62038. __decorate([
  62039. BABYLON.serialize()
  62040. ], FollowCamera.prototype, "rotationOffset", void 0);
  62041. __decorate([
  62042. BABYLON.serialize()
  62043. ], FollowCamera.prototype, "heightOffset", void 0);
  62044. __decorate([
  62045. BABYLON.serialize()
  62046. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  62047. __decorate([
  62048. BABYLON.serialize()
  62049. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  62050. __decorate([
  62051. BABYLON.serializeAsMeshReference("lockedTargetId")
  62052. ], FollowCamera.prototype, "lockedTarget", void 0);
  62053. return FollowCamera;
  62054. }(BABYLON.TargetCamera));
  62055. BABYLON.FollowCamera = FollowCamera;
  62056. var ArcFollowCamera = /** @class */ (function (_super) {
  62057. __extends(ArcFollowCamera, _super);
  62058. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  62059. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  62060. _this.alpha = alpha;
  62061. _this.beta = beta;
  62062. _this.radius = radius;
  62063. _this.target = target;
  62064. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  62065. _this.follow();
  62066. return _this;
  62067. }
  62068. ArcFollowCamera.prototype.follow = function () {
  62069. if (!this.target) {
  62070. return;
  62071. }
  62072. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  62073. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  62074. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  62075. var targetPosition = this.target.getAbsolutePosition();
  62076. this.position = targetPosition.add(this._cartesianCoordinates);
  62077. this.setTarget(targetPosition);
  62078. };
  62079. ArcFollowCamera.prototype._checkInputs = function () {
  62080. _super.prototype._checkInputs.call(this);
  62081. this.follow();
  62082. };
  62083. ArcFollowCamera.prototype.getClassName = function () {
  62084. return "ArcFollowCamera";
  62085. };
  62086. return ArcFollowCamera;
  62087. }(BABYLON.TargetCamera));
  62088. BABYLON.ArcFollowCamera = ArcFollowCamera;
  62089. })(BABYLON || (BABYLON = {}));
  62090. //# sourceMappingURL=babylon.followCamera.js.map
  62091. var BABYLON;
  62092. (function (BABYLON) {
  62093. // We're mainly based on the logic defined into the FreeCamera code
  62094. var UniversalCamera = /** @class */ (function (_super) {
  62095. __extends(UniversalCamera, _super);
  62096. //-- end properties for backward compatibility for inputs
  62097. function UniversalCamera(name, position, scene) {
  62098. var _this = _super.call(this, name, position, scene) || this;
  62099. _this.inputs.addGamepad();
  62100. return _this;
  62101. }
  62102. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  62103. //-- Begin properties for backward compatibility for inputs
  62104. get: function () {
  62105. var gamepad = this.inputs.attached["gamepad"];
  62106. if (gamepad)
  62107. return gamepad.gamepadAngularSensibility;
  62108. return 0;
  62109. },
  62110. set: function (value) {
  62111. var gamepad = this.inputs.attached["gamepad"];
  62112. if (gamepad)
  62113. gamepad.gamepadAngularSensibility = value;
  62114. },
  62115. enumerable: true,
  62116. configurable: true
  62117. });
  62118. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  62119. get: function () {
  62120. var gamepad = this.inputs.attached["gamepad"];
  62121. if (gamepad)
  62122. return gamepad.gamepadMoveSensibility;
  62123. return 0;
  62124. },
  62125. set: function (value) {
  62126. var gamepad = this.inputs.attached["gamepad"];
  62127. if (gamepad)
  62128. gamepad.gamepadMoveSensibility = value;
  62129. },
  62130. enumerable: true,
  62131. configurable: true
  62132. });
  62133. UniversalCamera.prototype.getClassName = function () {
  62134. return "UniversalCamera";
  62135. };
  62136. return UniversalCamera;
  62137. }(BABYLON.TouchCamera));
  62138. BABYLON.UniversalCamera = UniversalCamera;
  62139. })(BABYLON || (BABYLON = {}));
  62140. //# sourceMappingURL=babylon.universalCamera.js.map
  62141. var BABYLON;
  62142. (function (BABYLON) {
  62143. // We're mainly based on the logic defined into the FreeCamera code
  62144. var GamepadCamera = /** @class */ (function (_super) {
  62145. __extends(GamepadCamera, _super);
  62146. //-- end properties for backward compatibility for inputs
  62147. function GamepadCamera(name, position, scene) {
  62148. return _super.call(this, name, position, scene) || this;
  62149. }
  62150. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  62151. //-- Begin properties for backward compatibility for inputs
  62152. get: function () {
  62153. var gamepad = this.inputs.attached["gamepad"];
  62154. if (gamepad)
  62155. return gamepad.gamepadAngularSensibility;
  62156. return 0;
  62157. },
  62158. set: function (value) {
  62159. var gamepad = this.inputs.attached["gamepad"];
  62160. if (gamepad)
  62161. gamepad.gamepadAngularSensibility = value;
  62162. },
  62163. enumerable: true,
  62164. configurable: true
  62165. });
  62166. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  62167. get: function () {
  62168. var gamepad = this.inputs.attached["gamepad"];
  62169. if (gamepad)
  62170. return gamepad.gamepadMoveSensibility;
  62171. return 0;
  62172. },
  62173. set: function (value) {
  62174. var gamepad = this.inputs.attached["gamepad"];
  62175. if (gamepad)
  62176. gamepad.gamepadMoveSensibility = value;
  62177. },
  62178. enumerable: true,
  62179. configurable: true
  62180. });
  62181. GamepadCamera.prototype.getClassName = function () {
  62182. return "GamepadCamera";
  62183. };
  62184. return GamepadCamera;
  62185. }(BABYLON.UniversalCamera));
  62186. BABYLON.GamepadCamera = GamepadCamera;
  62187. })(BABYLON || (BABYLON = {}));
  62188. //# sourceMappingURL=babylon.gamepadCamera.js.map
  62189. var BABYLON;
  62190. (function (BABYLON) {
  62191. var PostProcessRenderPipelineManager = /** @class */ (function () {
  62192. function PostProcessRenderPipelineManager() {
  62193. this._renderPipelines = {};
  62194. }
  62195. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  62196. this._renderPipelines[renderPipeline._name] = renderPipeline;
  62197. };
  62198. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  62199. if (unique === void 0) { unique = false; }
  62200. var renderPipeline = this._renderPipelines[renderPipelineName];
  62201. if (!renderPipeline) {
  62202. return;
  62203. }
  62204. renderPipeline._attachCameras(cameras, unique);
  62205. };
  62206. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  62207. var renderPipeline = this._renderPipelines[renderPipelineName];
  62208. if (!renderPipeline) {
  62209. return;
  62210. }
  62211. renderPipeline._detachCameras(cameras);
  62212. };
  62213. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62214. var renderPipeline = this._renderPipelines[renderPipelineName];
  62215. if (!renderPipeline) {
  62216. return;
  62217. }
  62218. renderPipeline._enableEffect(renderEffectName, cameras);
  62219. };
  62220. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62221. var renderPipeline = this._renderPipelines[renderPipelineName];
  62222. if (!renderPipeline) {
  62223. return;
  62224. }
  62225. renderPipeline._disableEffect(renderEffectName, cameras);
  62226. };
  62227. PostProcessRenderPipelineManager.prototype.update = function () {
  62228. for (var renderPipelineName in this._renderPipelines) {
  62229. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62230. var pipeline = this._renderPipelines[renderPipelineName];
  62231. if (!pipeline.isSupported) {
  62232. pipeline.dispose();
  62233. delete this._renderPipelines[renderPipelineName];
  62234. }
  62235. else {
  62236. pipeline._update();
  62237. }
  62238. }
  62239. }
  62240. };
  62241. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  62242. for (var renderPipelineName in this._renderPipelines) {
  62243. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62244. var pipeline = this._renderPipelines[renderPipelineName];
  62245. pipeline._rebuild();
  62246. }
  62247. }
  62248. };
  62249. PostProcessRenderPipelineManager.prototype.dispose = function () {
  62250. for (var renderPipelineName in this._renderPipelines) {
  62251. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62252. var pipeline = this._renderPipelines[renderPipelineName];
  62253. pipeline.dispose();
  62254. }
  62255. }
  62256. };
  62257. return PostProcessRenderPipelineManager;
  62258. }());
  62259. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  62260. })(BABYLON || (BABYLON = {}));
  62261. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  62262. var BABYLON;
  62263. (function (BABYLON) {
  62264. /**
  62265. * This represents a set of one or more post processes in Babylon.
  62266. * A post process can be used to apply a shader to a texture after it is rendered.
  62267. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  62268. */
  62269. var PostProcessRenderEffect = /** @class */ (function () {
  62270. /**
  62271. * Instantiates a post process render effect.
  62272. * A post process can be used to apply a shader to a texture after it is rendered.
  62273. * @param engine The engine the effect is tied to
  62274. * @param name The name of the effect
  62275. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  62276. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  62277. */
  62278. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  62279. this._name = name;
  62280. this._singleInstance = singleInstance || true;
  62281. this._getPostProcesses = getPostProcesses;
  62282. this._cameras = {};
  62283. this._indicesForCamera = {};
  62284. this._postProcesses = {};
  62285. }
  62286. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  62287. /**
  62288. * Checks if all the post processes in the effect are supported.
  62289. */
  62290. get: function () {
  62291. for (var index in this._postProcesses) {
  62292. for (var ppIndex in this._postProcesses[index]) {
  62293. if (!this._postProcesses[index][ppIndex].isSupported) {
  62294. return false;
  62295. }
  62296. }
  62297. }
  62298. return true;
  62299. },
  62300. enumerable: true,
  62301. configurable: true
  62302. });
  62303. /**
  62304. * Updates the current state of the effect
  62305. */
  62306. PostProcessRenderEffect.prototype._update = function () {
  62307. };
  62308. /**
  62309. * Attaches the effect on cameras
  62310. * @param cameras The camera to attach to.
  62311. */
  62312. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  62313. var _this = this;
  62314. var cameraKey;
  62315. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62316. if (!cams) {
  62317. return;
  62318. }
  62319. for (var i = 0; i < cams.length; i++) {
  62320. var camera = cams[i];
  62321. var cameraName = camera.name;
  62322. if (this._singleInstance) {
  62323. cameraKey = 0;
  62324. }
  62325. else {
  62326. cameraKey = cameraName;
  62327. }
  62328. if (!this._postProcesses[cameraKey]) {
  62329. var postProcess = this._getPostProcesses();
  62330. if (postProcess) {
  62331. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  62332. }
  62333. }
  62334. if (!this._indicesForCamera[cameraName]) {
  62335. this._indicesForCamera[cameraName] = [];
  62336. }
  62337. this._postProcesses[cameraKey].forEach(function (postProcess) {
  62338. var index = camera.attachPostProcess(postProcess);
  62339. _this._indicesForCamera[cameraName].push(index);
  62340. });
  62341. if (!this._cameras[cameraName]) {
  62342. this._cameras[cameraName] = camera;
  62343. }
  62344. }
  62345. };
  62346. /**
  62347. * Detatches the effect on cameras
  62348. * @param cameras The camera to detatch from.
  62349. */
  62350. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  62351. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62352. if (!cams) {
  62353. return;
  62354. }
  62355. for (var i = 0; i < cams.length; i++) {
  62356. var camera = cams[i];
  62357. var cameraName = camera.name;
  62358. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  62359. camera.detachPostProcess(postProcess);
  62360. });
  62361. if (this._cameras[cameraName]) {
  62362. //this._indicesForCamera.splice(index, 1);
  62363. this._cameras[cameraName] = null;
  62364. }
  62365. }
  62366. };
  62367. /**
  62368. * Enables the effect on given cameras
  62369. * @param cameras The camera to enable.
  62370. */
  62371. PostProcessRenderEffect.prototype._enable = function (cameras) {
  62372. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62373. if (!cams) {
  62374. return;
  62375. }
  62376. for (var i = 0; i < cams.length; i++) {
  62377. var camera = cams[i];
  62378. var cameraName = camera.name;
  62379. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  62380. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  62381. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  62382. }
  62383. }
  62384. }
  62385. };
  62386. /**
  62387. * Disables the effect on the given cameras
  62388. * @param cameras The camera to disable.
  62389. */
  62390. PostProcessRenderEffect.prototype._disable = function (cameras) {
  62391. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62392. if (!cams) {
  62393. return;
  62394. }
  62395. for (var i = 0; i < cams.length; i++) {
  62396. var camera = cams[i];
  62397. var cameraName = camera.Name;
  62398. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  62399. }
  62400. };
  62401. /**
  62402. * Gets a list of the post processes contained in the effect.
  62403. * @param camera The camera to get the post processes on.
  62404. * @returns The list of the post processes in the effect.
  62405. */
  62406. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  62407. if (this._singleInstance) {
  62408. return this._postProcesses[0];
  62409. }
  62410. else {
  62411. if (!camera) {
  62412. return null;
  62413. }
  62414. return this._postProcesses[camera.name];
  62415. }
  62416. };
  62417. return PostProcessRenderEffect;
  62418. }());
  62419. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  62420. })(BABYLON || (BABYLON = {}));
  62421. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  62422. var BABYLON;
  62423. (function (BABYLON) {
  62424. var PostProcessRenderPipeline = /** @class */ (function () {
  62425. function PostProcessRenderPipeline(engine, name) {
  62426. this._name = name;
  62427. this._renderEffects = {};
  62428. this._renderEffectsForIsolatedPass = new Array();
  62429. this._cameras = [];
  62430. }
  62431. PostProcessRenderPipeline.prototype.getClassName = function () {
  62432. return "PostProcessRenderPipeline";
  62433. };
  62434. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  62435. get: function () {
  62436. for (var renderEffectName in this._renderEffects) {
  62437. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62438. if (!this._renderEffects[renderEffectName].isSupported) {
  62439. return false;
  62440. }
  62441. }
  62442. }
  62443. return true;
  62444. },
  62445. enumerable: true,
  62446. configurable: true
  62447. });
  62448. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  62449. this._renderEffects[renderEffect._name] = renderEffect;
  62450. };
  62451. // private
  62452. PostProcessRenderPipeline.prototype._rebuild = function () {
  62453. };
  62454. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62455. var renderEffects = this._renderEffects[renderEffectName];
  62456. if (!renderEffects) {
  62457. return;
  62458. }
  62459. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62460. };
  62461. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  62462. var renderEffects = this._renderEffects[renderEffectName];
  62463. if (!renderEffects) {
  62464. return;
  62465. }
  62466. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62467. };
  62468. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  62469. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62470. if (!cams) {
  62471. return;
  62472. }
  62473. var indicesToDelete = [];
  62474. var i;
  62475. for (i = 0; i < cams.length; i++) {
  62476. var camera = cams[i];
  62477. var cameraName = camera.name;
  62478. if (this._cameras.indexOf(camera) === -1) {
  62479. this._cameras[cameraName] = camera;
  62480. }
  62481. else if (unique) {
  62482. indicesToDelete.push(i);
  62483. }
  62484. }
  62485. for (i = 0; i < indicesToDelete.length; i++) {
  62486. cameras.splice(indicesToDelete[i], 1);
  62487. }
  62488. for (var renderEffectName in this._renderEffects) {
  62489. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62490. this._renderEffects[renderEffectName]._attachCameras(cams);
  62491. }
  62492. }
  62493. };
  62494. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  62495. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62496. if (!cams) {
  62497. return;
  62498. }
  62499. for (var renderEffectName in this._renderEffects) {
  62500. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62501. this._renderEffects[renderEffectName]._detachCameras(cams);
  62502. }
  62503. }
  62504. for (var i = 0; i < cams.length; i++) {
  62505. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  62506. }
  62507. };
  62508. PostProcessRenderPipeline.prototype._update = function () {
  62509. for (var renderEffectName in this._renderEffects) {
  62510. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62511. this._renderEffects[renderEffectName]._update();
  62512. }
  62513. }
  62514. for (var i = 0; i < this._cameras.length; i++) {
  62515. var cameraName = this._cameras[i].name;
  62516. if (this._renderEffectsForIsolatedPass[cameraName]) {
  62517. this._renderEffectsForIsolatedPass[cameraName]._update();
  62518. }
  62519. }
  62520. };
  62521. PostProcessRenderPipeline.prototype._reset = function () {
  62522. this._renderEffects = {};
  62523. this._renderEffectsForIsolatedPass = new Array();
  62524. };
  62525. PostProcessRenderPipeline.prototype.dispose = function () {
  62526. // Must be implemented by children
  62527. };
  62528. __decorate([
  62529. BABYLON.serialize()
  62530. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  62531. return PostProcessRenderPipeline;
  62532. }());
  62533. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  62534. })(BABYLON || (BABYLON = {}));
  62535. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  62536. var BABYLON;
  62537. (function (BABYLON) {
  62538. var DepthRenderer = /** @class */ (function () {
  62539. function DepthRenderer(scene, type) {
  62540. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  62541. var _this = this;
  62542. this._scene = scene;
  62543. var engine = scene.getEngine();
  62544. // Render target
  62545. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  62546. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62547. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62548. this._depthMap.refreshRate = 1;
  62549. this._depthMap.renderParticles = false;
  62550. this._depthMap.renderList = null;
  62551. // set default depth value to 1.0 (far away)
  62552. this._depthMap.onClearObservable.add(function (engine) {
  62553. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  62554. });
  62555. // Custom render function
  62556. var renderSubMesh = function (subMesh) {
  62557. var mesh = subMesh.getRenderingMesh();
  62558. var scene = _this._scene;
  62559. var engine = scene.getEngine();
  62560. var material = subMesh.getMaterial();
  62561. if (!material) {
  62562. return;
  62563. }
  62564. // Culling and reverse (right handed system)
  62565. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62566. // Managing instances
  62567. var batch = mesh._getInstancesRenderList(subMesh._id);
  62568. if (batch.mustReturn) {
  62569. return;
  62570. }
  62571. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62572. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  62573. engine.enableEffect(_this._effect);
  62574. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62575. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62576. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  62577. // Alpha test
  62578. if (material && material.needAlphaTesting()) {
  62579. var alphaTexture = material.getAlphaTestTexture();
  62580. if (alphaTexture) {
  62581. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62582. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62583. }
  62584. }
  62585. // Bones
  62586. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62587. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62588. }
  62589. // Draw
  62590. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62591. }
  62592. };
  62593. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62594. var index;
  62595. if (depthOnlySubMeshes.length) {
  62596. engine.setColorWrite(false);
  62597. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62598. renderSubMesh(depthOnlySubMeshes.data[index]);
  62599. }
  62600. engine.setColorWrite(true);
  62601. }
  62602. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62603. renderSubMesh(opaqueSubMeshes.data[index]);
  62604. }
  62605. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62606. renderSubMesh(alphaTestSubMeshes.data[index]);
  62607. }
  62608. };
  62609. }
  62610. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62611. var material = subMesh.getMaterial();
  62612. if (material.disableDepthWrite) {
  62613. return false;
  62614. }
  62615. var defines = [];
  62616. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62617. var mesh = subMesh.getMesh();
  62618. // Alpha test
  62619. if (material && material.needAlphaTesting()) {
  62620. defines.push("#define ALPHATEST");
  62621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62622. attribs.push(BABYLON.VertexBuffer.UVKind);
  62623. defines.push("#define UV1");
  62624. }
  62625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62626. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62627. defines.push("#define UV2");
  62628. }
  62629. }
  62630. // Bones
  62631. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62634. if (mesh.numBoneInfluencers > 4) {
  62635. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62636. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62637. }
  62638. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62639. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62640. }
  62641. else {
  62642. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62643. }
  62644. // Instances
  62645. if (useInstances) {
  62646. defines.push("#define INSTANCES");
  62647. attribs.push("world0");
  62648. attribs.push("world1");
  62649. attribs.push("world2");
  62650. attribs.push("world3");
  62651. }
  62652. // Get correct effect
  62653. var join = defines.join("\n");
  62654. if (this._cachedDefines !== join) {
  62655. this._cachedDefines = join;
  62656. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62657. }
  62658. return this._effect.isReady();
  62659. };
  62660. DepthRenderer.prototype.getDepthMap = function () {
  62661. return this._depthMap;
  62662. };
  62663. // Methods
  62664. DepthRenderer.prototype.dispose = function () {
  62665. this._depthMap.dispose();
  62666. };
  62667. return DepthRenderer;
  62668. }());
  62669. BABYLON.DepthRenderer = DepthRenderer;
  62670. })(BABYLON || (BABYLON = {}));
  62671. //# sourceMappingURL=babylon.depthRenderer.js.map
  62672. var BABYLON;
  62673. (function (BABYLON) {
  62674. var SSAORenderingPipeline = /** @class */ (function (_super) {
  62675. __extends(SSAORenderingPipeline, _super);
  62676. /**
  62677. * @constructor
  62678. * @param {string} name - The rendering pipeline name
  62679. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62680. * @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 }
  62681. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62682. */
  62683. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  62684. var _this = _super.call(this, scene.getEngine(), name) || this;
  62685. // Members
  62686. /**
  62687. * The PassPostProcess id in the pipeline that contains the original scene color
  62688. * @type {string}
  62689. */
  62690. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62691. /**
  62692. * The SSAO PostProcess id in the pipeline
  62693. * @type {string}
  62694. */
  62695. _this.SSAORenderEffect = "SSAORenderEffect";
  62696. /**
  62697. * The horizontal blur PostProcess id in the pipeline
  62698. * @type {string}
  62699. */
  62700. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62701. /**
  62702. * The vertical blur PostProcess id in the pipeline
  62703. * @type {string}
  62704. */
  62705. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62706. /**
  62707. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62708. * @type {string}
  62709. */
  62710. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62711. /**
  62712. * The output strength of the SSAO post-process. Default value is 1.0.
  62713. * @type {number}
  62714. */
  62715. _this.totalStrength = 1.0;
  62716. /**
  62717. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  62718. * @type {number}
  62719. */
  62720. _this.radius = 0.0001;
  62721. /**
  62722. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  62723. * Must not be equal to fallOff and superior to fallOff.
  62724. * Default value is 0.975
  62725. * @type {number}
  62726. */
  62727. _this.area = 0.0075;
  62728. /**
  62729. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  62730. * Must not be equal to area and inferior to area.
  62731. * Default value is 0.0
  62732. * @type {number}
  62733. */
  62734. _this.fallOff = 0.000001;
  62735. /**
  62736. * The base color of the SSAO post-process
  62737. * The final result is "base + ssao" between [0, 1]
  62738. * @type {number}
  62739. */
  62740. _this.base = 0.5;
  62741. _this._firstUpdate = true;
  62742. _this._scene = scene;
  62743. // Set up assets
  62744. _this._createRandomTexture();
  62745. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62746. var ssaoRatio = ratio.ssaoRatio || ratio;
  62747. var combineRatio = ratio.combineRatio || ratio;
  62748. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62749. _this._createSSAOPostProcess(ssaoRatio);
  62750. _this._createBlurPostProcess(ssaoRatio);
  62751. _this._createSSAOCombinePostProcess(combineRatio);
  62752. // Set up pipeline
  62753. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62754. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62755. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62756. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62757. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62758. // Finish
  62759. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62760. if (cameras)
  62761. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62762. return _this;
  62763. }
  62764. // Public Methods
  62765. /**
  62766. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62767. */
  62768. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62769. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62770. for (var i = 0; i < this._scene.cameras.length; i++) {
  62771. var camera = this._scene.cameras[i];
  62772. this._originalColorPostProcess.dispose(camera);
  62773. this._ssaoPostProcess.dispose(camera);
  62774. this._blurHPostProcess.dispose(camera);
  62775. this._blurVPostProcess.dispose(camera);
  62776. this._ssaoCombinePostProcess.dispose(camera);
  62777. }
  62778. this._randomTexture.dispose();
  62779. if (disableDepthRender)
  62780. this._scene.disableDepthRenderer();
  62781. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62782. _super.prototype.dispose.call(this);
  62783. };
  62784. // Private Methods
  62785. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62786. var _this = this;
  62787. var size = 16;
  62788. 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);
  62789. 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);
  62790. this._blurHPostProcess.onActivateObservable.add(function () {
  62791. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62792. _this._blurHPostProcess.kernel = size * dw;
  62793. });
  62794. this._blurVPostProcess.onActivateObservable.add(function () {
  62795. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62796. _this._blurVPostProcess.kernel = size * dw;
  62797. });
  62798. };
  62799. SSAORenderingPipeline.prototype._rebuild = function () {
  62800. this._firstUpdate = true;
  62801. _super.prototype._rebuild.call(this);
  62802. };
  62803. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62804. var _this = this;
  62805. var numSamples = 16;
  62806. var sampleSphere = [
  62807. 0.5381, 0.1856, -0.4319,
  62808. 0.1379, 0.2486, 0.4430,
  62809. 0.3371, 0.5679, -0.0057,
  62810. -0.6999, -0.0451, -0.0019,
  62811. 0.0689, -0.1598, -0.8547,
  62812. 0.0560, 0.0069, -0.1843,
  62813. -0.0146, 0.1402, 0.0762,
  62814. 0.0100, -0.1924, -0.0344,
  62815. -0.3577, -0.5301, -0.4358,
  62816. -0.3169, 0.1063, 0.0158,
  62817. 0.0103, -0.5869, 0.0046,
  62818. -0.0897, -0.4940, 0.3287,
  62819. 0.7119, -0.0154, -0.0918,
  62820. -0.0533, 0.0596, -0.5411,
  62821. 0.0352, -0.0631, 0.5460,
  62822. -0.4776, 0.2847, -0.0271
  62823. ];
  62824. var samplesFactor = 1.0 / numSamples;
  62825. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  62826. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62827. "area", "fallOff", "base", "range", "viewport"
  62828. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62829. this._ssaoPostProcess.onApply = function (effect) {
  62830. if (_this._firstUpdate) {
  62831. effect.setArray3("sampleSphere", sampleSphere);
  62832. effect.setFloat("samplesFactor", samplesFactor);
  62833. effect.setFloat("randTextureTiles", 4.0);
  62834. }
  62835. effect.setFloat("totalStrength", _this.totalStrength);
  62836. effect.setFloat("radius", _this.radius);
  62837. effect.setFloat("area", _this.area);
  62838. effect.setFloat("fallOff", _this.fallOff);
  62839. effect.setFloat("base", _this.base);
  62840. effect.setTexture("textureSampler", _this._depthTexture);
  62841. effect.setTexture("randomSampler", _this._randomTexture);
  62842. };
  62843. };
  62844. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62845. var _this = this;
  62846. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62847. this._ssaoCombinePostProcess.onApply = function (effect) {
  62848. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62849. };
  62850. };
  62851. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  62852. var size = 512;
  62853. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62854. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62855. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62856. var context = this._randomTexture.getContext();
  62857. var rand = function (min, max) {
  62858. return Math.random() * (max - min) + min;
  62859. };
  62860. var randVector = BABYLON.Vector3.Zero();
  62861. for (var x = 0; x < size; x++) {
  62862. for (var y = 0; y < size; y++) {
  62863. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  62864. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  62865. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  62866. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62867. context.fillRect(x, y, 1, 1);
  62868. }
  62869. }
  62870. this._randomTexture.update(false);
  62871. };
  62872. __decorate([
  62873. BABYLON.serialize()
  62874. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  62875. __decorate([
  62876. BABYLON.serialize()
  62877. ], SSAORenderingPipeline.prototype, "radius", void 0);
  62878. __decorate([
  62879. BABYLON.serialize()
  62880. ], SSAORenderingPipeline.prototype, "area", void 0);
  62881. __decorate([
  62882. BABYLON.serialize()
  62883. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  62884. __decorate([
  62885. BABYLON.serialize()
  62886. ], SSAORenderingPipeline.prototype, "base", void 0);
  62887. return SSAORenderingPipeline;
  62888. }(BABYLON.PostProcessRenderPipeline));
  62889. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  62890. })(BABYLON || (BABYLON = {}));
  62891. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  62892. var BABYLON;
  62893. (function (BABYLON) {
  62894. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  62895. __extends(SSAO2RenderingPipeline, _super);
  62896. /**
  62897. * @constructor
  62898. * @param {string} name - The rendering pipeline name
  62899. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62900. * @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 }
  62901. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62902. */
  62903. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  62904. var _this = _super.call(this, scene.getEngine(), name) || this;
  62905. // Members
  62906. /**
  62907. * The PassPostProcess id in the pipeline that contains the original scene color
  62908. * @type {string}
  62909. */
  62910. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62911. /**
  62912. * The SSAO PostProcess id in the pipeline
  62913. * @type {string}
  62914. */
  62915. _this.SSAORenderEffect = "SSAORenderEffect";
  62916. /**
  62917. * The horizontal blur PostProcess id in the pipeline
  62918. * @type {string}
  62919. */
  62920. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62921. /**
  62922. * The vertical blur PostProcess id in the pipeline
  62923. * @type {string}
  62924. */
  62925. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62926. /**
  62927. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62928. * @type {string}
  62929. */
  62930. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62931. /**
  62932. * The output strength of the SSAO post-process. Default value is 1.0.
  62933. * @type {number}
  62934. */
  62935. _this.totalStrength = 1.0;
  62936. /**
  62937. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  62938. * @type {number}
  62939. */
  62940. _this.maxZ = 100.0;
  62941. /**
  62942. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  62943. * @type {number}
  62944. */
  62945. _this.minZAspect = 0.2;
  62946. /**
  62947. * Number of samples used for the SSAO calculations. Default value is 8
  62948. * @type {number}
  62949. */
  62950. _this._samples = 8;
  62951. /**
  62952. * Are we using bilateral blur ?
  62953. * @type {boolean}
  62954. */
  62955. _this._expensiveBlur = true;
  62956. /**
  62957. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  62958. * @type {number}
  62959. */
  62960. _this.radius = 2.0;
  62961. /**
  62962. * The base color of the SSAO post-process
  62963. * The final result is "base + ssao" between [0, 1]
  62964. * @type {number}
  62965. */
  62966. _this.base = 0.1;
  62967. _this._firstUpdate = true;
  62968. _this._scene = scene;
  62969. if (!_this.isSupported) {
  62970. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  62971. return _this;
  62972. }
  62973. var ssaoRatio = ratio.ssaoRatio || ratio;
  62974. var blurRatio = ratio.blurRatio || ratio;
  62975. // Set up assets
  62976. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  62977. _this._createRandomTexture();
  62978. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  62979. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  62980. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62981. _this._createSSAOPostProcess(1.0);
  62982. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  62983. _this._createSSAOCombinePostProcess(blurRatio);
  62984. // Set up pipeline
  62985. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62986. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62987. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62988. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62989. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62990. // Finish
  62991. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62992. if (cameras)
  62993. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62994. return _this;
  62995. }
  62996. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62997. get: function () {
  62998. return this._samples;
  62999. },
  63000. set: function (n) {
  63001. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  63002. this._samples = n;
  63003. this._sampleSphere = this._generateHemisphere();
  63004. this._firstUpdate = true;
  63005. },
  63006. enumerable: true,
  63007. configurable: true
  63008. });
  63009. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  63010. get: function () {
  63011. return this._expensiveBlur;
  63012. },
  63013. set: function (b) {
  63014. 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"]);
  63015. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  63016. this._expensiveBlur = b;
  63017. this._firstUpdate = true;
  63018. },
  63019. enumerable: true,
  63020. configurable: true
  63021. });
  63022. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  63023. /**
  63024. * Support test.
  63025. * @type {boolean}
  63026. */
  63027. get: function () {
  63028. var engine = BABYLON.Engine.LastCreatedEngine;
  63029. if (!engine) {
  63030. return false;
  63031. }
  63032. return engine.getCaps().drawBuffersExtension;
  63033. },
  63034. enumerable: true,
  63035. configurable: true
  63036. });
  63037. // Public Methods
  63038. /**
  63039. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63040. */
  63041. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  63042. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  63043. for (var i = 0; i < this._scene.cameras.length; i++) {
  63044. var camera = this._scene.cameras[i];
  63045. this._originalColorPostProcess.dispose(camera);
  63046. this._ssaoPostProcess.dispose(camera);
  63047. this._blurHPostProcess.dispose(camera);
  63048. this._blurVPostProcess.dispose(camera);
  63049. this._ssaoCombinePostProcess.dispose(camera);
  63050. }
  63051. this._randomTexture.dispose();
  63052. if (disableGeometryBufferRenderer)
  63053. this._scene.disableGeometryBufferRenderer();
  63054. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63055. _super.prototype.dispose.call(this);
  63056. };
  63057. // Private Methods
  63058. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  63059. var _this = this;
  63060. this._samplerOffsets = [];
  63061. var expensive = this.expensiveBlur;
  63062. for (var i = -8; i < 8; i++) {
  63063. this._samplerOffsets.push(i * 2 + 0.5);
  63064. }
  63065. 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");
  63066. this._blurHPostProcess.onApply = function (effect) {
  63067. if (!_this._scene.activeCamera) {
  63068. return;
  63069. }
  63070. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  63071. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63072. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63073. effect.setFloat("radius", _this.radius);
  63074. effect.setTexture("depthSampler", _this._depthTexture);
  63075. if (_this._firstUpdate) {
  63076. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63077. }
  63078. };
  63079. 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");
  63080. this._blurVPostProcess.onApply = function (effect) {
  63081. if (!_this._scene.activeCamera) {
  63082. return;
  63083. }
  63084. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  63085. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63086. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63087. effect.setFloat("radius", _this.radius);
  63088. effect.setTexture("depthSampler", _this._depthTexture);
  63089. if (_this._firstUpdate) {
  63090. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63091. _this._firstUpdate = false;
  63092. }
  63093. };
  63094. };
  63095. SSAO2RenderingPipeline.prototype._rebuild = function () {
  63096. this._firstUpdate = true;
  63097. _super.prototype._rebuild.call(this);
  63098. };
  63099. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  63100. var numSamples = this.samples;
  63101. var result = [];
  63102. var vector, scale;
  63103. var rand = function (min, max) {
  63104. return Math.random() * (max - min) + min;
  63105. };
  63106. var i = 0;
  63107. while (i < numSamples) {
  63108. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  63109. vector.normalize();
  63110. scale = i / numSamples;
  63111. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  63112. vector.scaleInPlace(scale);
  63113. result.push(vector.x, vector.y, vector.z);
  63114. i++;
  63115. }
  63116. return result;
  63117. };
  63118. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63119. var _this = this;
  63120. var numSamples = this.samples;
  63121. this._sampleSphere = this._generateHemisphere();
  63122. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  63123. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63124. "base", "range", "projection", "near", "far", "texelSize",
  63125. "xViewport", "yViewport", "maxZ", "minZAspect"
  63126. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63127. this._ssaoPostProcess.onApply = function (effect) {
  63128. if (_this._firstUpdate) {
  63129. effect.setArray3("sampleSphere", _this._sampleSphere);
  63130. effect.setFloat("randTextureTiles", 4.0);
  63131. }
  63132. if (!_this._scene.activeCamera) {
  63133. return;
  63134. }
  63135. effect.setFloat("samplesFactor", 1 / _this.samples);
  63136. effect.setFloat("totalStrength", _this.totalStrength);
  63137. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  63138. effect.setFloat("radius", _this.radius);
  63139. effect.setFloat("maxZ", _this.maxZ);
  63140. effect.setFloat("minZAspect", _this.minZAspect);
  63141. effect.setFloat("base", _this.base);
  63142. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63143. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63144. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  63145. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  63146. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  63147. effect.setTexture("textureSampler", _this._depthTexture);
  63148. effect.setTexture("normalSampler", _this._normalTexture);
  63149. effect.setTexture("randomSampler", _this._randomTexture);
  63150. };
  63151. };
  63152. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63153. var _this = this;
  63154. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63155. this._ssaoCombinePostProcess.onApply = function (effect) {
  63156. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63157. };
  63158. };
  63159. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  63160. var size = 512;
  63161. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63162. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63163. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63164. var context = this._randomTexture.getContext();
  63165. var rand = function (min, max) {
  63166. return Math.random() * (max - min) + min;
  63167. };
  63168. var randVector = BABYLON.Vector3.Zero();
  63169. for (var x = 0; x < size; x++) {
  63170. for (var y = 0; y < size; y++) {
  63171. randVector.x = rand(0.0, 1.0);
  63172. randVector.y = rand(0.0, 1.0);
  63173. randVector.z = 0.0;
  63174. randVector.normalize();
  63175. randVector.scaleInPlace(255);
  63176. randVector.x = Math.floor(randVector.x);
  63177. randVector.y = Math.floor(randVector.y);
  63178. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63179. context.fillRect(x, y, 1, 1);
  63180. }
  63181. }
  63182. this._randomTexture.update(false);
  63183. };
  63184. __decorate([
  63185. BABYLON.serialize()
  63186. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  63187. __decorate([
  63188. BABYLON.serialize()
  63189. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  63190. __decorate([
  63191. BABYLON.serialize()
  63192. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  63193. __decorate([
  63194. BABYLON.serialize("samples")
  63195. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  63196. __decorate([
  63197. BABYLON.serialize("expensiveBlur")
  63198. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  63199. __decorate([
  63200. BABYLON.serialize()
  63201. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  63202. __decorate([
  63203. BABYLON.serialize()
  63204. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  63205. return SSAO2RenderingPipeline;
  63206. }(BABYLON.PostProcessRenderPipeline));
  63207. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  63208. })(BABYLON || (BABYLON = {}));
  63209. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  63210. // BABYLON.JS Chromatic Aberration GLSL Shader
  63211. // Author: Olivier Guyot
  63212. // Separates very slightly R, G and B colors on the edges of the screen
  63213. // Inspired by Francois Tarlier & Martins Upitis
  63214. var BABYLON;
  63215. (function (BABYLON) {
  63216. var LensRenderingPipeline = /** @class */ (function (_super) {
  63217. __extends(LensRenderingPipeline, _super);
  63218. /**
  63219. * @constructor
  63220. *
  63221. * Effect parameters are as follow:
  63222. * {
  63223. * chromatic_aberration: number; // from 0 to x (1 for realism)
  63224. * edge_blur: number; // from 0 to x (1 for realism)
  63225. * distortion: number; // from 0 to x (1 for realism)
  63226. * grain_amount: number; // from 0 to 1
  63227. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  63228. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  63229. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  63230. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  63231. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  63232. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  63233. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  63234. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  63235. * }
  63236. * Note: if an effect parameter is unset, effect is disabled
  63237. *
  63238. * @param {string} name - The rendering pipeline name
  63239. * @param {object} parameters - An object containing all parameters (see above)
  63240. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63241. * @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)
  63242. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63243. */
  63244. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  63245. if (ratio === void 0) { ratio = 1.0; }
  63246. var _this = _super.call(this, scene.getEngine(), name) || this;
  63247. // Lens effects can be of the following:
  63248. // - chromatic aberration (slight shift of RGB colors)
  63249. // - blur on the edge of the lens
  63250. // - lens distortion
  63251. // - depth-of-field blur & highlights enhancing
  63252. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  63253. // - grain effect (noise or custom texture)
  63254. // Two additional texture samplers are needed:
  63255. // - depth map (for depth-of-field)
  63256. // - grain texture
  63257. /**
  63258. * The chromatic aberration PostProcess id in the pipeline
  63259. * @type {string}
  63260. */
  63261. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  63262. /**
  63263. * The highlights enhancing PostProcess id in the pipeline
  63264. * @type {string}
  63265. */
  63266. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  63267. /**
  63268. * The depth-of-field PostProcess id in the pipeline
  63269. * @type {string}
  63270. */
  63271. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  63272. _this._scene = scene;
  63273. // Fetch texture samplers
  63274. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63275. if (parameters.grain_texture) {
  63276. _this._grainTexture = parameters.grain_texture;
  63277. }
  63278. else {
  63279. _this._createGrainTexture();
  63280. }
  63281. // save parameters
  63282. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  63283. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  63284. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  63285. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  63286. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  63287. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  63288. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  63289. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  63290. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  63291. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  63292. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  63293. // Create effects
  63294. _this._createChromaticAberrationPostProcess(ratio);
  63295. _this._createHighlightsPostProcess(ratio);
  63296. _this._createDepthOfFieldPostProcess(ratio / 4);
  63297. // Set up pipeline
  63298. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  63299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  63300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  63301. if (_this._highlightsGain === -1) {
  63302. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  63303. }
  63304. // Finish
  63305. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63306. if (cameras) {
  63307. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63308. }
  63309. return _this;
  63310. }
  63311. // public methods (self explanatory)
  63312. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  63313. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  63314. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  63315. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  63316. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  63317. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  63318. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  63319. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  63320. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  63321. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  63322. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  63323. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  63324. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  63325. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  63326. };
  63327. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  63328. this._highlightsPostProcess.updateEffect();
  63329. };
  63330. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  63331. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  63332. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  63333. this._highlightsGain = amount;
  63334. };
  63335. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  63336. if (this._highlightsGain === -1) {
  63337. this._highlightsGain = 1.0;
  63338. }
  63339. this._highlightsThreshold = amount;
  63340. };
  63341. LensRenderingPipeline.prototype.disableHighlights = function () {
  63342. this._highlightsGain = -1;
  63343. };
  63344. /**
  63345. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  63346. */
  63347. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63348. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63349. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63350. this._chromaticAberrationPostProcess = null;
  63351. this._highlightsPostProcess = null;
  63352. this._depthOfFieldPostProcess = null;
  63353. this._grainTexture.dispose();
  63354. if (disableDepthRender)
  63355. this._scene.disableDepthRenderer();
  63356. };
  63357. // colors shifting and distortion
  63358. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  63359. var _this = this;
  63360. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  63361. [], // samplers
  63362. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63363. this._chromaticAberrationPostProcess.onApply = function (effect) {
  63364. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  63365. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63366. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63367. };
  63368. };
  63369. // highlights enhancing
  63370. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  63371. var _this = this;
  63372. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  63373. [], // samplers
  63374. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  63375. this._highlightsPostProcess.onApply = function (effect) {
  63376. effect.setFloat('gain', _this._highlightsGain);
  63377. effect.setFloat('threshold', _this._highlightsThreshold);
  63378. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  63379. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63380. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63381. };
  63382. };
  63383. // colors shifting and distortion
  63384. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  63385. var _this = this;
  63386. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  63387. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  63388. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  63389. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63390. this._depthOfFieldPostProcess.onApply = function (effect) {
  63391. effect.setTexture("depthSampler", _this._depthTexture);
  63392. effect.setTexture("grainSampler", _this._grainTexture);
  63393. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  63394. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  63395. effect.setFloat('grain_amount', _this._grainAmount);
  63396. effect.setBool('blur_noise', _this._blurNoise);
  63397. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63398. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63399. effect.setFloat('distortion', _this._distortion);
  63400. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63401. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63402. effect.setFloat('aperture', _this._dofAperture);
  63403. effect.setFloat('darken', _this._dofDarken);
  63404. effect.setFloat('edge_blur', _this._edgeBlur);
  63405. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63406. if (_this._scene.activeCamera) {
  63407. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63408. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63409. }
  63410. };
  63411. };
  63412. // creates a black and white random noise texture, 512x512
  63413. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63414. var size = 512;
  63415. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63416. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63417. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63418. var context = this._grainTexture.getContext();
  63419. var rand = function (min, max) {
  63420. return Math.random() * (max - min) + min;
  63421. };
  63422. var value;
  63423. for (var x = 0; x < size; x++) {
  63424. for (var y = 0; y < size; y++) {
  63425. value = Math.floor(rand(0.42, 0.58) * 255);
  63426. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63427. context.fillRect(x, y, 1, 1);
  63428. }
  63429. }
  63430. this._grainTexture.update(false);
  63431. };
  63432. return LensRenderingPipeline;
  63433. }(BABYLON.PostProcessRenderPipeline));
  63434. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63435. })(BABYLON || (BABYLON = {}));
  63436. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63437. var BABYLON;
  63438. (function (BABYLON) {
  63439. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63440. __extends(StandardRenderingPipeline, _super);
  63441. /**
  63442. * @constructor
  63443. * @param {string} name - The rendering pipeline name
  63444. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63445. * @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)
  63446. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63447. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63448. */
  63449. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63450. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63451. var _this = _super.call(this, scene.getEngine(), name) || this;
  63452. _this.downSampleX4PostProcess = null;
  63453. _this.brightPassPostProcess = null;
  63454. _this.blurHPostProcesses = [];
  63455. _this.blurVPostProcesses = [];
  63456. _this.textureAdderPostProcess = null;
  63457. _this.volumetricLightPostProcess = null;
  63458. _this.volumetricLightSmoothXPostProcess = null;
  63459. _this.volumetricLightSmoothYPostProcess = null;
  63460. _this.volumetricLightMergePostProces = null;
  63461. _this.volumetricLightFinalPostProcess = null;
  63462. _this.luminancePostProcess = null;
  63463. _this.luminanceDownSamplePostProcesses = [];
  63464. _this.hdrPostProcess = null;
  63465. _this.textureAdderFinalPostProcess = null;
  63466. _this.lensFlareFinalPostProcess = null;
  63467. _this.hdrFinalPostProcess = null;
  63468. _this.lensFlarePostProcess = null;
  63469. _this.lensFlareComposePostProcess = null;
  63470. _this.motionBlurPostProcess = null;
  63471. _this.depthOfFieldPostProcess = null;
  63472. // Values
  63473. _this.brightThreshold = 1.0;
  63474. _this.blurWidth = 512.0;
  63475. _this.horizontalBlur = false;
  63476. _this.exposure = 1.0;
  63477. _this.lensTexture = null;
  63478. _this.volumetricLightCoefficient = 0.2;
  63479. _this.volumetricLightPower = 4.0;
  63480. _this.volumetricLightBlurScale = 64.0;
  63481. _this.sourceLight = null;
  63482. _this.hdrMinimumLuminance = 1.0;
  63483. _this.hdrDecreaseRate = 0.5;
  63484. _this.hdrIncreaseRate = 0.5;
  63485. _this.lensColorTexture = null;
  63486. _this.lensFlareStrength = 20.0;
  63487. _this.lensFlareGhostDispersal = 1.4;
  63488. _this.lensFlareHaloWidth = 0.7;
  63489. _this.lensFlareDistortionStrength = 16.0;
  63490. _this.lensStarTexture = null;
  63491. _this.lensFlareDirtTexture = null;
  63492. _this.depthOfFieldDistance = 10.0;
  63493. _this.depthOfFieldBlurWidth = 64.0;
  63494. _this.motionStrength = 1.0;
  63495. // IAnimatable
  63496. _this.animations = [];
  63497. _this._currentDepthOfFieldSource = null;
  63498. _this._hdrCurrentLuminance = 1.0;
  63499. // Getters and setters
  63500. _this._bloomEnabled = true;
  63501. _this._depthOfFieldEnabled = false;
  63502. _this._vlsEnabled = false;
  63503. _this._lensFlareEnabled = false;
  63504. _this._hdrEnabled = false;
  63505. _this._motionBlurEnabled = false;
  63506. _this._motionBlurSamples = 64.0;
  63507. _this._volumetricLightStepsCount = 50.0;
  63508. _this._cameras = cameras || [];
  63509. // Initialize
  63510. _this._scene = scene;
  63511. _this._basePostProcess = originalPostProcess;
  63512. _this._ratio = ratio;
  63513. // Misc
  63514. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63515. // Finish
  63516. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63517. _this._buildPipeline();
  63518. return _this;
  63519. }
  63520. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  63521. get: function () {
  63522. return this._bloomEnabled;
  63523. },
  63524. set: function (enabled) {
  63525. if (this._bloomEnabled === enabled) {
  63526. return;
  63527. }
  63528. this._bloomEnabled = enabled;
  63529. this._buildPipeline();
  63530. },
  63531. enumerable: true,
  63532. configurable: true
  63533. });
  63534. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63535. get: function () {
  63536. return this._depthOfFieldEnabled;
  63537. },
  63538. set: function (enabled) {
  63539. if (this._depthOfFieldEnabled === enabled) {
  63540. return;
  63541. }
  63542. this._depthOfFieldEnabled = enabled;
  63543. this._buildPipeline();
  63544. },
  63545. enumerable: true,
  63546. configurable: true
  63547. });
  63548. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63549. get: function () {
  63550. return this._lensFlareEnabled;
  63551. },
  63552. set: function (enabled) {
  63553. if (this._lensFlareEnabled === enabled) {
  63554. return;
  63555. }
  63556. this._lensFlareEnabled = enabled;
  63557. this._buildPipeline();
  63558. },
  63559. enumerable: true,
  63560. configurable: true
  63561. });
  63562. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  63563. get: function () {
  63564. return this._hdrEnabled;
  63565. },
  63566. set: function (enabled) {
  63567. if (this._hdrEnabled === enabled) {
  63568. return;
  63569. }
  63570. this._hdrEnabled = enabled;
  63571. this._buildPipeline();
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  63577. get: function () {
  63578. return this._vlsEnabled;
  63579. },
  63580. set: function (enabled) {
  63581. if (this._vlsEnabled === enabled) {
  63582. return;
  63583. }
  63584. if (enabled) {
  63585. var geometry = this._scene.enableGeometryBufferRenderer();
  63586. if (!geometry) {
  63587. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63588. return;
  63589. }
  63590. }
  63591. this._vlsEnabled = enabled;
  63592. this._buildPipeline();
  63593. },
  63594. enumerable: true,
  63595. configurable: true
  63596. });
  63597. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63598. get: function () {
  63599. return this._motionBlurEnabled;
  63600. },
  63601. set: function (enabled) {
  63602. if (this._motionBlurEnabled === enabled) {
  63603. return;
  63604. }
  63605. this._motionBlurEnabled = enabled;
  63606. this._buildPipeline();
  63607. },
  63608. enumerable: true,
  63609. configurable: true
  63610. });
  63611. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63612. get: function () {
  63613. return this._volumetricLightStepsCount;
  63614. },
  63615. set: function (count) {
  63616. if (this.volumetricLightPostProcess) {
  63617. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63618. }
  63619. this._volumetricLightStepsCount = count;
  63620. },
  63621. enumerable: true,
  63622. configurable: true
  63623. });
  63624. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63625. get: function () {
  63626. return this._motionBlurSamples;
  63627. },
  63628. set: function (samples) {
  63629. if (this.motionBlurPostProcess) {
  63630. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63631. }
  63632. this._motionBlurSamples = samples;
  63633. },
  63634. enumerable: true,
  63635. configurable: true
  63636. });
  63637. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63638. var _this = this;
  63639. var ratio = this._ratio;
  63640. var scene = this._scene;
  63641. this._disposePostProcesses();
  63642. this._reset();
  63643. // Create pass post-process
  63644. if (!this._basePostProcess) {
  63645. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63646. this.originalPostProcess.onApply = function (effect) {
  63647. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63648. };
  63649. }
  63650. else {
  63651. this.originalPostProcess = this._basePostProcess;
  63652. }
  63653. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63654. this._currentDepthOfFieldSource = this.originalPostProcess;
  63655. if (this._vlsEnabled) {
  63656. // Create volumetric light
  63657. this._createVolumetricLightPostProcess(scene, ratio);
  63658. // Create volumetric light final post-process
  63659. 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);
  63660. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63661. }
  63662. if (this._bloomEnabled) {
  63663. // Create down sample X4 post-process
  63664. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63665. // Create bright pass post-process
  63666. this._createBrightPassPostProcess(scene, ratio / 2);
  63667. // Create gaussian blur post-processes (down sampling blurs)
  63668. this._createBlurPostProcesses(scene, ratio / 4, 1);
  63669. // Create texture adder post-process
  63670. this._createTextureAdderPostProcess(scene, ratio);
  63671. // Create depth-of-field source post-process
  63672. 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);
  63673. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63674. }
  63675. if (this._lensFlareEnabled) {
  63676. // Create lens flare post-process
  63677. this._createLensFlarePostProcess(scene, ratio);
  63678. // Create depth-of-field source post-process post lens-flare and disable it now
  63679. 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);
  63680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  63681. }
  63682. if (this._hdrEnabled) {
  63683. // Create luminance
  63684. this._createLuminancePostProcesses(scene, this._floatTextureType);
  63685. // Create HDR
  63686. this._createHdrPostProcess(scene, ratio);
  63687. // Create depth-of-field source post-process post hdr and disable it now
  63688. 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);
  63689. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  63690. }
  63691. if (this._depthOfFieldEnabled) {
  63692. // Create gaussian blur used by depth-of-field
  63693. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  63694. // Create depth-of-field post-process
  63695. this._createDepthOfFieldPostProcess(scene, ratio);
  63696. }
  63697. if (this._motionBlurEnabled) {
  63698. // Create motion blur post-process
  63699. this._createMotionBlurPostProcess(scene, ratio);
  63700. }
  63701. if (this._cameras !== null) {
  63702. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63703. }
  63704. };
  63705. // Down Sample X4 Post-Processs
  63706. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63707. var _this = this;
  63708. var downSampleX4Offsets = new Array(32);
  63709. 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);
  63710. this.downSampleX4PostProcess.onApply = function (effect) {
  63711. var id = 0;
  63712. var width = _this.downSampleX4PostProcess.width;
  63713. var height = _this.downSampleX4PostProcess.height;
  63714. for (var i = -2; i < 2; i++) {
  63715. for (var j = -2; j < 2; j++) {
  63716. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  63717. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  63718. id += 2;
  63719. }
  63720. }
  63721. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63722. };
  63723. // Add to pipeline
  63724. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63725. };
  63726. // Brightpass Post-Process
  63727. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63728. var _this = this;
  63729. var brightOffsets = new Array(8);
  63730. 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);
  63731. this.brightPassPostProcess.onApply = function (effect) {
  63732. var sU = (1.0 / _this.brightPassPostProcess.width);
  63733. var sV = (1.0 / _this.brightPassPostProcess.height);
  63734. brightOffsets[0] = -0.5 * sU;
  63735. brightOffsets[1] = 0.5 * sV;
  63736. brightOffsets[2] = 0.5 * sU;
  63737. brightOffsets[3] = 0.5 * sV;
  63738. brightOffsets[4] = -0.5 * sU;
  63739. brightOffsets[5] = -0.5 * sV;
  63740. brightOffsets[6] = 0.5 * sU;
  63741. brightOffsets[7] = -0.5 * sV;
  63742. effect.setArray2("dsOffsets", brightOffsets);
  63743. effect.setFloat("brightThreshold", _this.brightThreshold);
  63744. };
  63745. // Add to pipeline
  63746. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63747. };
  63748. // Create blur H&V post-processes
  63749. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63750. var _this = this;
  63751. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63752. var engine = scene.getEngine();
  63753. 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);
  63754. 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);
  63755. blurX.onActivateObservable.add(function () {
  63756. var dw = blurX.width / engine.getRenderWidth();
  63757. blurX.kernel = _this[blurWidthKey] * dw;
  63758. });
  63759. blurY.onActivateObservable.add(function () {
  63760. var dw = blurY.height / engine.getRenderHeight();
  63761. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63762. });
  63763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63765. this.blurHPostProcesses.push(blurX);
  63766. this.blurVPostProcesses.push(blurY);
  63767. };
  63768. // Create texture adder post-process
  63769. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63770. var _this = this;
  63771. 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);
  63772. this.textureAdderPostProcess.onApply = function (effect) {
  63773. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63774. effect.setTexture("lensSampler", _this.lensTexture);
  63775. effect.setFloat("exposure", _this.exposure);
  63776. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63777. };
  63778. // Add to pipeline
  63779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63780. };
  63781. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63782. var _this = this;
  63783. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63784. geometryRenderer.enablePosition = true;
  63785. var geometry = geometryRenderer.getGBuffer();
  63786. // Base post-process
  63787. 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));
  63788. var depthValues = BABYLON.Vector2.Zero();
  63789. this.volumetricLightPostProcess.onApply = function (effect) {
  63790. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63791. var generator = _this.sourceLight.getShadowGenerator();
  63792. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63793. effect.setTexture("positionSampler", geometry.textures[2]);
  63794. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63795. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63796. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63797. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63798. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63799. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63800. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63801. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63802. effect.setVector2("depthValues", depthValues);
  63803. }
  63804. };
  63805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63806. // Smooth
  63807. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63808. // Merge
  63809. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63810. this.volumetricLightMergePostProces.onApply = function (effect) {
  63811. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63812. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63813. };
  63814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63815. };
  63816. // Create luminance
  63817. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63818. var _this = this;
  63819. // Create luminance
  63820. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63821. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63822. var offsets = [];
  63823. this.luminancePostProcess.onApply = function (effect) {
  63824. var sU = (1.0 / _this.luminancePostProcess.width);
  63825. var sV = (1.0 / _this.luminancePostProcess.height);
  63826. offsets[0] = -0.5 * sU;
  63827. offsets[1] = 0.5 * sV;
  63828. offsets[2] = 0.5 * sU;
  63829. offsets[3] = 0.5 * sV;
  63830. offsets[4] = -0.5 * sU;
  63831. offsets[5] = -0.5 * sV;
  63832. offsets[6] = 0.5 * sU;
  63833. offsets[7] = -0.5 * sV;
  63834. effect.setArray2("lumOffsets", offsets);
  63835. };
  63836. // Add to pipeline
  63837. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  63838. // Create down sample luminance
  63839. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  63840. var size = Math.pow(3, i);
  63841. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  63842. if (i === 0) {
  63843. defines += "#define FINAL_DOWN_SAMPLER";
  63844. }
  63845. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  63846. this.luminanceDownSamplePostProcesses.push(postProcess);
  63847. }
  63848. // Create callbacks and add effects
  63849. var lastLuminance = this.luminancePostProcess;
  63850. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  63851. var downSampleOffsets = new Array(18);
  63852. pp.onApply = function (effect) {
  63853. if (!lastLuminance) {
  63854. return;
  63855. }
  63856. var id = 0;
  63857. for (var x = -1; x < 2; x++) {
  63858. for (var y = -1; y < 2; y++) {
  63859. downSampleOffsets[id] = x / lastLuminance.width;
  63860. downSampleOffsets[id + 1] = y / lastLuminance.height;
  63861. id += 2;
  63862. }
  63863. }
  63864. effect.setArray2("dsOffsets", downSampleOffsets);
  63865. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  63866. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63867. lastLuminance = _this.luminancePostProcess;
  63868. }
  63869. else {
  63870. lastLuminance = pp;
  63871. }
  63872. };
  63873. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63874. pp.onAfterRender = function (effect) {
  63875. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  63876. 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);
  63877. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  63878. };
  63879. }
  63880. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  63881. });
  63882. };
  63883. // Create HDR post-process
  63884. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  63885. var _this = this;
  63886. 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);
  63887. var outputLiminance = 1;
  63888. var time = 0;
  63889. var lastTime = 0;
  63890. this.hdrPostProcess.onApply = function (effect) {
  63891. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  63892. time += scene.getEngine().getDeltaTime();
  63893. if (outputLiminance < 0) {
  63894. outputLiminance = _this._hdrCurrentLuminance;
  63895. }
  63896. else {
  63897. var dt = (lastTime - time) / 1000.0;
  63898. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  63899. outputLiminance += _this.hdrDecreaseRate * dt;
  63900. }
  63901. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  63902. outputLiminance -= _this.hdrIncreaseRate * dt;
  63903. }
  63904. else {
  63905. outputLiminance = _this._hdrCurrentLuminance;
  63906. }
  63907. }
  63908. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  63909. effect.setFloat("averageLuminance", outputLiminance);
  63910. lastTime = time;
  63911. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  63912. };
  63913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  63914. };
  63915. // Create lens flare post-process
  63916. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63917. var _this = this;
  63918. 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);
  63919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  63920. this._createBlurPostProcesses(scene, ratio / 4, 2);
  63921. 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);
  63922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  63923. var resolution = new BABYLON.Vector2(0, 0);
  63924. // Lens flare
  63925. this.lensFlarePostProcess.onApply = function (effect) {
  63926. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  63927. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63928. effect.setFloat("strength", _this.lensFlareStrength);
  63929. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63930. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63931. // Shift
  63932. resolution.x = _this.lensFlarePostProcess.width;
  63933. resolution.y = _this.lensFlarePostProcess.height;
  63934. effect.setVector2("resolution", resolution);
  63935. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63936. };
  63937. // Compose
  63938. 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);
  63939. 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);
  63940. this.lensFlareComposePostProcess.onApply = function (effect) {
  63941. if (!_this._scene.activeCamera) {
  63942. return;
  63943. }
  63944. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63945. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63946. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63947. // Lens start rotation matrix
  63948. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  63949. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  63950. 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));
  63951. camRot *= 4.0;
  63952. 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);
  63953. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  63954. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  63955. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  63956. };
  63957. };
  63958. // Create depth-of-field post-process
  63959. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63960. var _this = this;
  63961. 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);
  63962. this.depthOfFieldPostProcess.onApply = function (effect) {
  63963. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63964. effect.setTexture("depthSampler", _this._getDepthTexture());
  63965. effect.setFloat("distance", _this.depthOfFieldDistance);
  63966. };
  63967. // Add to pipeline
  63968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63969. };
  63970. // Create motion blur post-process
  63971. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  63972. var _this = this;
  63973. 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);
  63974. var motionScale = 0;
  63975. var prevViewProjection = BABYLON.Matrix.Identity();
  63976. var invViewProjection = BABYLON.Matrix.Identity();
  63977. var viewProjection = BABYLON.Matrix.Identity();
  63978. var screenSize = BABYLON.Vector2.Zero();
  63979. this.motionBlurPostProcess.onApply = function (effect) {
  63980. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  63981. viewProjection.invertToRef(invViewProjection);
  63982. effect.setMatrix("inverseViewProjection", invViewProjection);
  63983. effect.setMatrix("prevViewProjection", prevViewProjection);
  63984. prevViewProjection = viewProjection;
  63985. screenSize.x = _this.motionBlurPostProcess.width;
  63986. screenSize.y = _this.motionBlurPostProcess.height;
  63987. effect.setVector2("screenSize", screenSize);
  63988. motionScale = scene.getEngine().getFps() / 60.0;
  63989. effect.setFloat("motionScale", motionScale);
  63990. effect.setFloat("motionStrength", _this.motionStrength);
  63991. effect.setTexture("depthSampler", _this._getDepthTexture());
  63992. };
  63993. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63994. };
  63995. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63996. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63997. var renderer = this._scene.enableGeometryBufferRenderer();
  63998. return renderer.getGBuffer().textures[0];
  63999. }
  64000. return this._scene.enableDepthRenderer().getDepthMap();
  64001. };
  64002. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  64003. for (var i = 0; i < this._cameras.length; i++) {
  64004. var camera = this._cameras[i];
  64005. if (this.originalPostProcess) {
  64006. this.originalPostProcess.dispose(camera);
  64007. }
  64008. if (this.downSampleX4PostProcess) {
  64009. this.downSampleX4PostProcess.dispose(camera);
  64010. }
  64011. if (this.brightPassPostProcess) {
  64012. this.brightPassPostProcess.dispose(camera);
  64013. }
  64014. if (this.textureAdderPostProcess) {
  64015. this.textureAdderPostProcess.dispose(camera);
  64016. }
  64017. if (this.textureAdderFinalPostProcess) {
  64018. this.textureAdderFinalPostProcess.dispose(camera);
  64019. }
  64020. if (this.volumetricLightPostProcess) {
  64021. this.volumetricLightPostProcess.dispose(camera);
  64022. }
  64023. if (this.volumetricLightSmoothXPostProcess) {
  64024. this.volumetricLightSmoothXPostProcess.dispose(camera);
  64025. }
  64026. if (this.volumetricLightSmoothYPostProcess) {
  64027. this.volumetricLightSmoothYPostProcess.dispose(camera);
  64028. }
  64029. if (this.volumetricLightMergePostProces) {
  64030. this.volumetricLightMergePostProces.dispose(camera);
  64031. }
  64032. if (this.volumetricLightFinalPostProcess) {
  64033. this.volumetricLightFinalPostProcess.dispose(camera);
  64034. }
  64035. if (this.lensFlarePostProcess) {
  64036. this.lensFlarePostProcess.dispose(camera);
  64037. }
  64038. if (this.lensFlareComposePostProcess) {
  64039. this.lensFlareComposePostProcess.dispose(camera);
  64040. }
  64041. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  64042. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  64043. }
  64044. if (this.luminancePostProcess) {
  64045. this.luminancePostProcess.dispose(camera);
  64046. }
  64047. if (this.hdrPostProcess) {
  64048. this.hdrPostProcess.dispose(camera);
  64049. }
  64050. if (this.hdrFinalPostProcess) {
  64051. this.hdrFinalPostProcess.dispose(camera);
  64052. }
  64053. if (this.depthOfFieldPostProcess) {
  64054. this.depthOfFieldPostProcess.dispose(camera);
  64055. }
  64056. if (this.motionBlurPostProcess) {
  64057. this.motionBlurPostProcess.dispose(camera);
  64058. }
  64059. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  64060. this.blurHPostProcesses[j].dispose(camera);
  64061. }
  64062. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  64063. this.blurVPostProcesses[j].dispose(camera);
  64064. }
  64065. }
  64066. this.originalPostProcess = null;
  64067. this.downSampleX4PostProcess = null;
  64068. this.brightPassPostProcess = null;
  64069. this.textureAdderPostProcess = null;
  64070. this.textureAdderFinalPostProcess = null;
  64071. this.volumetricLightPostProcess = null;
  64072. this.volumetricLightSmoothXPostProcess = null;
  64073. this.volumetricLightSmoothYPostProcess = null;
  64074. this.volumetricLightMergePostProces = null;
  64075. this.volumetricLightFinalPostProcess = null;
  64076. this.lensFlarePostProcess = null;
  64077. this.lensFlareComposePostProcess = null;
  64078. this.luminancePostProcess = null;
  64079. this.hdrPostProcess = null;
  64080. this.hdrFinalPostProcess = null;
  64081. this.depthOfFieldPostProcess = null;
  64082. this.motionBlurPostProcess = null;
  64083. this.luminanceDownSamplePostProcesses = [];
  64084. this.blurHPostProcesses = [];
  64085. this.blurVPostProcesses = [];
  64086. };
  64087. // Dispose
  64088. StandardRenderingPipeline.prototype.dispose = function () {
  64089. this._disposePostProcesses();
  64090. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64091. _super.prototype.dispose.call(this);
  64092. };
  64093. // Serialize rendering pipeline
  64094. StandardRenderingPipeline.prototype.serialize = function () {
  64095. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64096. serializationObject.customType = "StandardRenderingPipeline";
  64097. return serializationObject;
  64098. };
  64099. /**
  64100. * Static members
  64101. */
  64102. // Parse serialized pipeline
  64103. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64104. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  64105. };
  64106. // Luminance steps
  64107. StandardRenderingPipeline.LuminanceSteps = 6;
  64108. __decorate([
  64109. BABYLON.serialize()
  64110. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  64111. __decorate([
  64112. BABYLON.serialize()
  64113. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  64114. __decorate([
  64115. BABYLON.serialize()
  64116. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  64117. __decorate([
  64118. BABYLON.serialize()
  64119. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  64120. __decorate([
  64121. BABYLON.serializeAsTexture("lensTexture")
  64122. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  64123. __decorate([
  64124. BABYLON.serialize()
  64125. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  64126. __decorate([
  64127. BABYLON.serialize()
  64128. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  64129. __decorate([
  64130. BABYLON.serialize()
  64131. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  64132. __decorate([
  64133. BABYLON.serialize()
  64134. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  64135. __decorate([
  64136. BABYLON.serialize()
  64137. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  64138. __decorate([
  64139. BABYLON.serialize()
  64140. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  64141. __decorate([
  64142. BABYLON.serializeAsTexture("lensColorTexture")
  64143. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  64144. __decorate([
  64145. BABYLON.serialize()
  64146. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  64147. __decorate([
  64148. BABYLON.serialize()
  64149. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  64150. __decorate([
  64151. BABYLON.serialize()
  64152. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  64153. __decorate([
  64154. BABYLON.serialize()
  64155. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  64156. __decorate([
  64157. BABYLON.serializeAsTexture("lensStarTexture")
  64158. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  64159. __decorate([
  64160. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  64161. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  64162. __decorate([
  64163. BABYLON.serialize()
  64164. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  64165. __decorate([
  64166. BABYLON.serialize()
  64167. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  64168. __decorate([
  64169. BABYLON.serialize()
  64170. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  64171. __decorate([
  64172. BABYLON.serialize()
  64173. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  64174. __decorate([
  64175. BABYLON.serialize()
  64176. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  64177. __decorate([
  64178. BABYLON.serialize()
  64179. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  64180. __decorate([
  64181. BABYLON.serialize()
  64182. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  64183. __decorate([
  64184. BABYLON.serialize()
  64185. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  64186. __decorate([
  64187. BABYLON.serialize()
  64188. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  64189. __decorate([
  64190. BABYLON.serialize()
  64191. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  64192. __decorate([
  64193. BABYLON.serialize()
  64194. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  64195. __decorate([
  64196. BABYLON.serialize()
  64197. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  64198. return StandardRenderingPipeline;
  64199. }(BABYLON.PostProcessRenderPipeline));
  64200. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  64201. })(BABYLON || (BABYLON = {}));
  64202. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  64203. var BABYLON;
  64204. (function (BABYLON) {
  64205. var FxaaPostProcess = /** @class */ (function (_super) {
  64206. __extends(FxaaPostProcess, _super);
  64207. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64208. if (camera === void 0) { camera = null; }
  64209. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64210. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  64211. _this.onApplyObservable.add(function (effect) {
  64212. var texelSize = _this.texelSize;
  64213. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  64214. });
  64215. return _this;
  64216. }
  64217. return FxaaPostProcess;
  64218. }(BABYLON.PostProcess));
  64219. BABYLON.FxaaPostProcess = FxaaPostProcess;
  64220. })(BABYLON || (BABYLON = {}));
  64221. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  64222. var BABYLON;
  64223. (function (BABYLON) {
  64224. /**
  64225. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  64226. */
  64227. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  64228. __extends(CircleOfConfusionPostProcess, _super);
  64229. /**
  64230. * Creates a new instance of @see CircleOfConfusionPostProcess
  64231. * @param name The name of the effect.
  64232. * @param scene The scene the effect belongs to.
  64233. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  64234. * @param options The required width/height ratio to downsize to before computing the render pass.
  64235. * @param camera The camera to apply the render pass to.
  64236. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64237. * @param engine The engine which the post process will be applied. (default: current engine)
  64238. * @param reusable If the post process can be reused on the same frame. (default: false)
  64239. * @param textureType Type of textures used when performing the post process. (default: 0)
  64240. */
  64241. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  64242. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64243. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64244. /**
  64245. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  64246. */
  64247. _this.lensSize = 50;
  64248. /**
  64249. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64250. */
  64251. _this.fStop = 1.4;
  64252. /**
  64253. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64254. */
  64255. _this.focusDistance = 2000;
  64256. /**
  64257. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  64258. */
  64259. _this.focalLength = 50;
  64260. _this.onApplyObservable.add(function (effect) {
  64261. effect.setTexture("depthSampler", depthTexture);
  64262. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  64263. var aperture = _this.lensSize / _this.fStop;
  64264. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  64265. effect.setFloat('focusDistance', _this.focusDistance);
  64266. effect.setFloat('cocPrecalculation', cocPrecalculation);
  64267. if (scene.activeCamera) {
  64268. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64269. }
  64270. });
  64271. return _this;
  64272. }
  64273. return CircleOfConfusionPostProcess;
  64274. }(BABYLON.PostProcess));
  64275. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  64276. })(BABYLON || (BABYLON = {}));
  64277. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  64278. var BABYLON;
  64279. (function (BABYLON) {
  64280. /**
  64281. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  64282. */
  64283. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  64284. __extends(DepthOfFieldMergePostProcess, _super);
  64285. /**
  64286. * Creates a new instance of @see CircleOfConfusionPostProcess
  64287. * @param name The name of the effect.
  64288. * @param original The non-blurred image to be modified
  64289. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  64290. * @param options The required width/height ratio to downsize to before computing the render pass.
  64291. * @param camera The camera to apply the render pass to.
  64292. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64293. * @param engine The engine which the post process will be applied. (default: current engine)
  64294. * @param reusable If the post process can be reused on the same frame. (default: false)
  64295. * @param textureType Type of textures used when performing the post process. (default: 0)
  64296. */
  64297. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  64298. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64299. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64300. _this.onApplyObservable.add(function (effect) {
  64301. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  64302. effect.setTextureFromPostProcess("originalSampler", original);
  64303. });
  64304. return _this;
  64305. }
  64306. return DepthOfFieldMergePostProcess;
  64307. }(BABYLON.PostProcess));
  64308. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  64309. })(BABYLON || (BABYLON = {}));
  64310. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  64311. var BABYLON;
  64312. (function (BABYLON) {
  64313. /**
  64314. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  64315. */
  64316. var DepthOfFieldEffect = /** @class */ (function (_super) {
  64317. __extends(DepthOfFieldEffect, _super);
  64318. /**
  64319. * Creates a new instance of @see DepthOfFieldEffect
  64320. * @param scene The scene the effect belongs to.
  64321. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  64322. */
  64323. function DepthOfFieldEffect(scene, pipelineTextureType) {
  64324. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  64325. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this.circleOfConfusion, _this.depthOfFieldPass, _this.depthOfFieldBlurY, _this.depthOfFieldBlurX, _this.depthOfFieldMerge]; }, true) || this;
  64326. // Enable and get current depth map
  64327. var depthMap = scene.enableDepthRenderer().getDepthMap();
  64328. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  64329. _this.circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64330. // Capture circle of confusion texture
  64331. _this.depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64332. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  64333. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  64334. _this.depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this.circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64335. _this.depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64336. // Merge blurred images with original image based on circleOfConfusion
  64337. _this.depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this.circleOfConfusion, _this.depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64338. return _this;
  64339. }
  64340. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  64341. get: function () {
  64342. return this.depthOfFieldBlurX.kernel;
  64343. },
  64344. /**
  64345. * The size of the kernel to be used for the blur
  64346. */
  64347. set: function (value) {
  64348. this.depthOfFieldBlurX.kernel = value;
  64349. this.depthOfFieldBlurY.kernel = value;
  64350. },
  64351. enumerable: true,
  64352. configurable: true
  64353. });
  64354. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  64355. get: function () {
  64356. return this.circleOfConfusion.focalLength;
  64357. },
  64358. /**
  64359. * The focal the length of the camera used in the effect
  64360. */
  64361. set: function (value) {
  64362. this.circleOfConfusion.focalLength = value;
  64363. },
  64364. enumerable: true,
  64365. configurable: true
  64366. });
  64367. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  64368. get: function () {
  64369. return this.circleOfConfusion.fStop;
  64370. },
  64371. /**
  64372. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64373. */
  64374. set: function (value) {
  64375. this.circleOfConfusion.fStop = value;
  64376. },
  64377. enumerable: true,
  64378. configurable: true
  64379. });
  64380. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  64381. get: function () {
  64382. return this.circleOfConfusion.focusDistance;
  64383. },
  64384. /**
  64385. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64386. */
  64387. set: function (value) {
  64388. this.circleOfConfusion.focusDistance = value;
  64389. },
  64390. enumerable: true,
  64391. configurable: true
  64392. });
  64393. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  64394. get: function () {
  64395. return this.circleOfConfusion.lensSize;
  64396. },
  64397. /**
  64398. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  64399. */
  64400. set: function (value) {
  64401. this.circleOfConfusion.lensSize = value;
  64402. },
  64403. enumerable: true,
  64404. configurable: true
  64405. });
  64406. /**
  64407. * Disposes each of the internal effects for a given camera.
  64408. * @param camera The camera to dispose the effect on.
  64409. */
  64410. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  64411. this.depthOfFieldPass.dispose(camera);
  64412. this.circleOfConfusion.dispose(camera);
  64413. this.depthOfFieldBlurX.dispose(camera);
  64414. this.depthOfFieldBlurY.dispose(camera);
  64415. this.depthOfFieldMerge.dispose(camera);
  64416. };
  64417. return DepthOfFieldEffect;
  64418. }(BABYLON.PostProcessRenderEffect));
  64419. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  64420. })(BABYLON || (BABYLON = {}));
  64421. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  64422. var BABYLON;
  64423. (function (BABYLON) {
  64424. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  64425. __extends(DefaultRenderingPipeline, _super);
  64426. /**
  64427. * @constructor
  64428. * @param {string} name - The rendering pipeline name
  64429. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64430. * @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)
  64431. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64432. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  64433. */
  64434. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  64435. if (automaticBuild === void 0) { automaticBuild = true; }
  64436. var _this = _super.call(this, scene.getEngine(), name) || this;
  64437. _this.PassPostProcessId = "PassPostProcessEffect";
  64438. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  64439. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  64440. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  64441. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  64442. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  64443. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  64444. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  64445. // IAnimatable
  64446. _this.animations = [];
  64447. // Values
  64448. _this._bloomEnabled = false;
  64449. _this._depthOfFieldEnabled = false;
  64450. _this._fxaaEnabled = false;
  64451. _this._imageProcessingEnabled = true;
  64452. _this._bloomScale = 0.6;
  64453. _this._buildAllowed = true;
  64454. /**
  64455. * Specifies the size of the bloom blur kernel, relative to the final output size
  64456. */
  64457. _this.bloomKernel = 64;
  64458. /**
  64459. * Specifies the weight of the bloom in the final rendering
  64460. */
  64461. _this._bloomWeight = 0.15;
  64462. _this._cameras = cameras || [];
  64463. _this._buildAllowed = automaticBuild;
  64464. // Initialize
  64465. _this._scene = scene;
  64466. var caps = _this._scene.getEngine().getCaps();
  64467. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  64468. // Misc
  64469. if (_this._hdr) {
  64470. if (caps.textureHalfFloatRender) {
  64471. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64472. }
  64473. else if (caps.textureFloatRender) {
  64474. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64475. }
  64476. }
  64477. else {
  64478. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64479. }
  64480. // Attach
  64481. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64482. _this._buildPipeline();
  64483. return _this;
  64484. }
  64485. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  64486. get: function () {
  64487. return this._bloomWeight;
  64488. },
  64489. set: function (value) {
  64490. if (this._bloomWeight === value) {
  64491. return;
  64492. }
  64493. this._bloomWeight = value;
  64494. if (this._hdr && this.copyBack) {
  64495. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  64496. }
  64497. },
  64498. enumerable: true,
  64499. configurable: true
  64500. });
  64501. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  64502. get: function () {
  64503. return this._bloomScale;
  64504. },
  64505. set: function (value) {
  64506. if (this._bloomScale === value) {
  64507. return;
  64508. }
  64509. this._bloomScale = value;
  64510. this._buildPipeline();
  64511. },
  64512. enumerable: true,
  64513. configurable: true
  64514. });
  64515. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  64516. get: function () {
  64517. return this._bloomEnabled;
  64518. },
  64519. set: function (enabled) {
  64520. if (this._bloomEnabled === enabled) {
  64521. return;
  64522. }
  64523. this._bloomEnabled = enabled;
  64524. this._buildPipeline();
  64525. },
  64526. enumerable: true,
  64527. configurable: true
  64528. });
  64529. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  64530. /**
  64531. * If the depth of field is enabled.
  64532. */
  64533. get: function () {
  64534. return this._depthOfFieldEnabled;
  64535. },
  64536. set: function (enabled) {
  64537. if (this._depthOfFieldEnabled === enabled) {
  64538. return;
  64539. }
  64540. this._depthOfFieldEnabled = enabled;
  64541. this._buildPipeline();
  64542. },
  64543. enumerable: true,
  64544. configurable: true
  64545. });
  64546. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  64547. get: function () {
  64548. return this._fxaaEnabled;
  64549. },
  64550. set: function (enabled) {
  64551. if (this._fxaaEnabled === enabled) {
  64552. return;
  64553. }
  64554. this._fxaaEnabled = enabled;
  64555. this._buildPipeline();
  64556. },
  64557. enumerable: true,
  64558. configurable: true
  64559. });
  64560. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  64561. get: function () {
  64562. return this._imageProcessingEnabled;
  64563. },
  64564. set: function (enabled) {
  64565. if (this._imageProcessingEnabled === enabled) {
  64566. return;
  64567. }
  64568. this._imageProcessingEnabled = enabled;
  64569. this._buildPipeline();
  64570. },
  64571. enumerable: true,
  64572. configurable: true
  64573. });
  64574. /**
  64575. * Force the compilation of the entire pipeline.
  64576. */
  64577. DefaultRenderingPipeline.prototype.prepare = function () {
  64578. var previousState = this._buildAllowed;
  64579. this._buildAllowed = true;
  64580. this._buildPipeline();
  64581. this._buildAllowed = previousState;
  64582. };
  64583. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  64584. var _this = this;
  64585. if (!this._buildAllowed) {
  64586. return;
  64587. }
  64588. var engine = this._scene.getEngine();
  64589. this._disposePostProcesses();
  64590. this._reset();
  64591. if (this.bloomEnabled) {
  64592. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64593. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  64594. if (!this._hdr) {
  64595. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64596. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  64597. this.highlights.autoClear = false;
  64598. this.highlights.alwaysForcePOT = true;
  64599. }
  64600. 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);
  64601. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  64602. this.blurX.alwaysForcePOT = true;
  64603. this.blurX.autoClear = false;
  64604. this.blurX.onActivateObservable.add(function () {
  64605. var dw = _this.blurX.width / engine.getRenderWidth(true);
  64606. _this.blurX.kernel = _this.bloomKernel * dw;
  64607. });
  64608. 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);
  64609. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  64610. this.blurY.alwaysForcePOT = true;
  64611. this.blurY.autoClear = false;
  64612. this.blurY.onActivateObservable.add(function () {
  64613. var dh = _this.blurY.height / engine.getRenderHeight(true);
  64614. _this.blurY.kernel = _this.bloomKernel * dh;
  64615. });
  64616. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64617. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  64618. this.copyBack.alwaysForcePOT = true;
  64619. if (this._hdr) {
  64620. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  64621. var w = this.bloomWeight;
  64622. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  64623. }
  64624. else {
  64625. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  64626. }
  64627. this.copyBack.autoClear = false;
  64628. }
  64629. if (this.depthOfFieldEnabled) {
  64630. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  64631. this.addEffect(this.depthOfField);
  64632. }
  64633. if (this._imageProcessingEnabled) {
  64634. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64635. if (this._hdr) {
  64636. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  64637. }
  64638. else {
  64639. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  64640. }
  64641. }
  64642. if (this.fxaaEnabled) {
  64643. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64644. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  64645. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64646. }
  64647. else if (this._hdr && this.imageProcessing) {
  64648. this.finalMerge = this.imageProcessing;
  64649. }
  64650. else {
  64651. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64652. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  64653. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64654. }
  64655. if (this.bloomEnabled) {
  64656. if (this._hdr) {
  64657. this.copyBack.shareOutputWith(this.blurX);
  64658. if (this.imageProcessing) {
  64659. this.imageProcessing.shareOutputWith(this.pass);
  64660. this.imageProcessing.autoClear = false;
  64661. }
  64662. else if (this.fxaa) {
  64663. this.fxaa.shareOutputWith(this.pass);
  64664. }
  64665. else {
  64666. this.finalMerge.shareOutputWith(this.pass);
  64667. }
  64668. }
  64669. else {
  64670. if (this.fxaa) {
  64671. this.fxaa.shareOutputWith(this.pass);
  64672. }
  64673. else {
  64674. this.finalMerge.shareOutputWith(this.pass);
  64675. }
  64676. }
  64677. }
  64678. if (this._cameras !== null) {
  64679. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64680. }
  64681. };
  64682. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  64683. for (var i = 0; i < this._cameras.length; i++) {
  64684. var camera = this._cameras[i];
  64685. if (this.pass) {
  64686. this.pass.dispose(camera);
  64687. }
  64688. if (this.highlights) {
  64689. this.highlights.dispose(camera);
  64690. }
  64691. if (this.blurX) {
  64692. this.blurX.dispose(camera);
  64693. }
  64694. if (this.blurY) {
  64695. this.blurY.dispose(camera);
  64696. }
  64697. if (this.copyBack) {
  64698. this.copyBack.dispose(camera);
  64699. }
  64700. if (this.imageProcessing) {
  64701. this.imageProcessing.dispose(camera);
  64702. }
  64703. if (this.fxaa) {
  64704. this.fxaa.dispose(camera);
  64705. }
  64706. if (this.finalMerge) {
  64707. this.finalMerge.dispose(camera);
  64708. }
  64709. if (this.depthOfField) {
  64710. this.depthOfField.disposeEffects(camera);
  64711. }
  64712. }
  64713. this.pass = null;
  64714. this.highlights = null;
  64715. this.blurX = null;
  64716. this.blurY = null;
  64717. this.copyBack = null;
  64718. this.imageProcessing = null;
  64719. this.fxaa = null;
  64720. this.finalMerge = null;
  64721. this.depthOfField = null;
  64722. };
  64723. // Dispose
  64724. DefaultRenderingPipeline.prototype.dispose = function () {
  64725. this._disposePostProcesses();
  64726. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64727. _super.prototype.dispose.call(this);
  64728. };
  64729. // Serialize rendering pipeline
  64730. DefaultRenderingPipeline.prototype.serialize = function () {
  64731. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64732. serializationObject.customType = "DefaultRenderingPipeline";
  64733. return serializationObject;
  64734. };
  64735. // Parse serialized pipeline
  64736. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64737. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  64738. };
  64739. __decorate([
  64740. BABYLON.serialize()
  64741. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  64742. __decorate([
  64743. BABYLON.serialize()
  64744. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  64745. __decorate([
  64746. BABYLON.serialize()
  64747. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  64748. __decorate([
  64749. BABYLON.serialize()
  64750. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  64751. __decorate([
  64752. BABYLON.serialize()
  64753. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  64754. __decorate([
  64755. BABYLON.serialize()
  64756. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  64757. __decorate([
  64758. BABYLON.serialize()
  64759. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  64760. __decorate([
  64761. BABYLON.serialize()
  64762. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  64763. __decorate([
  64764. BABYLON.serialize()
  64765. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  64766. return DefaultRenderingPipeline;
  64767. }(BABYLON.PostProcessRenderPipeline));
  64768. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  64769. })(BABYLON || (BABYLON = {}));
  64770. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  64771. var BABYLON;
  64772. (function (BABYLON) {
  64773. /**
  64774. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  64775. */
  64776. var GeometryBufferRenderer = /** @class */ (function () {
  64777. /**
  64778. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  64779. * @param scene The scene the buffer belongs to
  64780. * @param ratio How big is the buffer related to the main canvas.
  64781. */
  64782. function GeometryBufferRenderer(scene, ratio) {
  64783. if (ratio === void 0) { ratio = 1; }
  64784. this._enablePosition = false;
  64785. this._scene = scene;
  64786. this._ratio = ratio;
  64787. // Render target
  64788. this._createRenderTargets();
  64789. }
  64790. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  64791. /**
  64792. * Set the render list (meshes to be rendered) used in the G buffer.
  64793. */
  64794. set: function (meshes) {
  64795. this._multiRenderTarget.renderList = meshes;
  64796. },
  64797. enumerable: true,
  64798. configurable: true
  64799. });
  64800. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  64801. /**
  64802. * Gets wether or not G buffer are supported by the running hardware.
  64803. * This requires draw buffer supports
  64804. */
  64805. get: function () {
  64806. return this._multiRenderTarget.isSupported;
  64807. },
  64808. enumerable: true,
  64809. configurable: true
  64810. });
  64811. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  64812. /**
  64813. * Gets wether or not position are enabled for the G buffer.
  64814. */
  64815. get: function () {
  64816. return this._enablePosition;
  64817. },
  64818. /**
  64819. * Sets wether or not position are enabled for the G buffer.
  64820. */
  64821. set: function (enable) {
  64822. this._enablePosition = enable;
  64823. this.dispose();
  64824. this._createRenderTargets();
  64825. },
  64826. enumerable: true,
  64827. configurable: true
  64828. });
  64829. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  64830. /**
  64831. * Gets the scene associated with the buffer.
  64832. */
  64833. get: function () {
  64834. return this._scene;
  64835. },
  64836. enumerable: true,
  64837. configurable: true
  64838. });
  64839. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  64840. /**
  64841. * Gets the ratio used by the buffer during its creation.
  64842. * How big is the buffer related to the main canvas.
  64843. */
  64844. get: function () {
  64845. return this._ratio;
  64846. },
  64847. enumerable: true,
  64848. configurable: true
  64849. });
  64850. /**
  64851. * Checks wether everything is ready to render a submesh to the G buffer.
  64852. * @param subMesh the submesh to check readiness for
  64853. * @param useInstances is the mesh drawn using instance or not
  64854. * @returns true if ready otherwise false
  64855. */
  64856. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  64857. var material = subMesh.getMaterial();
  64858. if (material && material.disableDepthWrite) {
  64859. return false;
  64860. }
  64861. var defines = [];
  64862. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  64863. var mesh = subMesh.getMesh();
  64864. // Alpha test
  64865. if (material && material.needAlphaTesting()) {
  64866. defines.push("#define ALPHATEST");
  64867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64868. attribs.push(BABYLON.VertexBuffer.UVKind);
  64869. defines.push("#define UV1");
  64870. }
  64871. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64872. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64873. defines.push("#define UV2");
  64874. }
  64875. }
  64876. // Buffers
  64877. if (this._enablePosition) {
  64878. defines.push("#define POSITION");
  64879. }
  64880. // Bones
  64881. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64882. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64883. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64884. if (mesh.numBoneInfluencers > 4) {
  64885. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64886. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64887. }
  64888. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64889. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64890. }
  64891. else {
  64892. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64893. }
  64894. // Instances
  64895. if (useInstances) {
  64896. defines.push("#define INSTANCES");
  64897. attribs.push("world0");
  64898. attribs.push("world1");
  64899. attribs.push("world2");
  64900. attribs.push("world3");
  64901. }
  64902. // Get correct effect
  64903. var join = defines.join("\n");
  64904. if (this._cachedDefines !== join) {
  64905. this._cachedDefines = join;
  64906. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  64907. }
  64908. return this._effect.isReady();
  64909. };
  64910. /**
  64911. * Gets the current underlying G Buffer.
  64912. * @returns the buffer
  64913. */
  64914. GeometryBufferRenderer.prototype.getGBuffer = function () {
  64915. return this._multiRenderTarget;
  64916. };
  64917. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  64918. /**
  64919. * Gets the number of samples used to render the buffer (anti aliasing).
  64920. */
  64921. get: function () {
  64922. return this._multiRenderTarget.samples;
  64923. },
  64924. /**
  64925. * Sets the number of samples used to render the buffer (anti aliasing).
  64926. */
  64927. set: function (value) {
  64928. this._multiRenderTarget.samples = value;
  64929. },
  64930. enumerable: true,
  64931. configurable: true
  64932. });
  64933. /**
  64934. * Disposes the renderer and frees up associated resources.
  64935. */
  64936. GeometryBufferRenderer.prototype.dispose = function () {
  64937. this.getGBuffer().dispose();
  64938. };
  64939. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  64940. var _this = this;
  64941. var engine = this._scene.getEngine();
  64942. var count = this._enablePosition ? 3 : 2;
  64943. 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 });
  64944. if (!this.isSupported) {
  64945. return;
  64946. }
  64947. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64948. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64949. this._multiRenderTarget.refreshRate = 1;
  64950. this._multiRenderTarget.renderParticles = false;
  64951. this._multiRenderTarget.renderList = null;
  64952. // set default depth value to 1.0 (far away)
  64953. this._multiRenderTarget.onClearObservable.add(function (engine) {
  64954. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  64955. });
  64956. // Custom render function
  64957. var renderSubMesh = function (subMesh) {
  64958. var mesh = subMesh.getRenderingMesh();
  64959. var scene = _this._scene;
  64960. var engine = scene.getEngine();
  64961. var material = subMesh.getMaterial();
  64962. if (!material) {
  64963. return;
  64964. }
  64965. // Culling
  64966. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64967. // Managing instances
  64968. var batch = mesh._getInstancesRenderList(subMesh._id);
  64969. if (batch.mustReturn) {
  64970. return;
  64971. }
  64972. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64973. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  64974. engine.enableEffect(_this._effect);
  64975. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64976. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64977. _this._effect.setMatrix("view", scene.getViewMatrix());
  64978. // Alpha test
  64979. if (material && material.needAlphaTesting()) {
  64980. var alphaTexture = material.getAlphaTestTexture();
  64981. if (alphaTexture) {
  64982. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64983. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64984. }
  64985. }
  64986. // Bones
  64987. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64988. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64989. }
  64990. // Draw
  64991. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64992. }
  64993. };
  64994. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64995. var index;
  64996. if (depthOnlySubMeshes.length) {
  64997. engine.setColorWrite(false);
  64998. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64999. renderSubMesh(depthOnlySubMeshes.data[index]);
  65000. }
  65001. engine.setColorWrite(true);
  65002. }
  65003. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65004. renderSubMesh(opaqueSubMeshes.data[index]);
  65005. }
  65006. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65007. renderSubMesh(alphaTestSubMeshes.data[index]);
  65008. }
  65009. };
  65010. };
  65011. return GeometryBufferRenderer;
  65012. }());
  65013. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  65014. })(BABYLON || (BABYLON = {}));
  65015. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  65016. var BABYLON;
  65017. (function (BABYLON) {
  65018. var RefractionPostProcess = /** @class */ (function (_super) {
  65019. __extends(RefractionPostProcess, _super);
  65020. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  65021. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  65022. _this.color = color;
  65023. _this.depth = depth;
  65024. _this.colorLevel = colorLevel;
  65025. _this.onActivateObservable.add(function (cam) {
  65026. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  65027. });
  65028. _this.onApplyObservable.add(function (effect) {
  65029. effect.setColor3("baseColor", _this.color);
  65030. effect.setFloat("depth", _this.depth);
  65031. effect.setFloat("colorLevel", _this.colorLevel);
  65032. effect.setTexture("refractionSampler", _this._refRexture);
  65033. });
  65034. return _this;
  65035. }
  65036. // Methods
  65037. RefractionPostProcess.prototype.dispose = function (camera) {
  65038. if (this._refRexture) {
  65039. this._refRexture.dispose();
  65040. }
  65041. _super.prototype.dispose.call(this, camera);
  65042. };
  65043. return RefractionPostProcess;
  65044. }(BABYLON.PostProcess));
  65045. BABYLON.RefractionPostProcess = RefractionPostProcess;
  65046. })(BABYLON || (BABYLON = {}));
  65047. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  65048. var BABYLON;
  65049. (function (BABYLON) {
  65050. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  65051. __extends(BlackAndWhitePostProcess, _super);
  65052. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  65053. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  65054. _this.degree = 1;
  65055. _this.onApplyObservable.add(function (effect) {
  65056. effect.setFloat("degree", _this.degree);
  65057. });
  65058. return _this;
  65059. }
  65060. return BlackAndWhitePostProcess;
  65061. }(BABYLON.PostProcess));
  65062. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  65063. })(BABYLON || (BABYLON = {}));
  65064. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  65065. var BABYLON;
  65066. (function (BABYLON) {
  65067. var ConvolutionPostProcess = /** @class */ (function (_super) {
  65068. __extends(ConvolutionPostProcess, _super);
  65069. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  65070. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  65071. _this.kernel = kernel;
  65072. _this.onApply = function (effect) {
  65073. effect.setFloat2("screenSize", _this.width, _this.height);
  65074. effect.setArray("kernel", _this.kernel);
  65075. };
  65076. return _this;
  65077. }
  65078. // Statics
  65079. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  65080. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  65081. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  65082. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  65083. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  65084. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  65085. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  65086. return ConvolutionPostProcess;
  65087. }(BABYLON.PostProcess));
  65088. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  65089. })(BABYLON || (BABYLON = {}));
  65090. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  65091. var BABYLON;
  65092. (function (BABYLON) {
  65093. var FilterPostProcess = /** @class */ (function (_super) {
  65094. __extends(FilterPostProcess, _super);
  65095. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  65096. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  65097. _this.kernelMatrix = kernelMatrix;
  65098. _this.onApply = function (effect) {
  65099. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  65100. };
  65101. return _this;
  65102. }
  65103. return FilterPostProcess;
  65104. }(BABYLON.PostProcess));
  65105. BABYLON.FilterPostProcess = FilterPostProcess;
  65106. })(BABYLON || (BABYLON = {}));
  65107. //# sourceMappingURL=babylon.filterPostProcess.js.map
  65108. var BABYLON;
  65109. (function (BABYLON) {
  65110. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  65111. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  65112. __extends(VolumetricLightScatteringPostProcess, _super);
  65113. /**
  65114. * @constructor
  65115. * @param {string} name - The post-process name
  65116. * @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)
  65117. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  65118. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  65119. * @param {number} samples - The post-process quality, default 100
  65120. * @param {number} samplingMode - The post-process filtering mode
  65121. * @param {BABYLON.Engine} engine - The babylon engine
  65122. * @param {boolean} reusable - If the post-process is reusable
  65123. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  65124. */
  65125. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  65126. if (samples === void 0) { samples = 100; }
  65127. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65128. 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;
  65129. _this._screenCoordinates = BABYLON.Vector2.Zero();
  65130. /**
  65131. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  65132. * @type {Vector3}
  65133. */
  65134. _this.customMeshPosition = BABYLON.Vector3.Zero();
  65135. /**
  65136. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  65137. * @type {boolean}
  65138. */
  65139. _this.useCustomMeshPosition = false;
  65140. /**
  65141. * If the post-process should inverse the light scattering direction
  65142. * @type {boolean}
  65143. */
  65144. _this.invert = true;
  65145. /**
  65146. * Array containing the excluded meshes not rendered in the internal pass
  65147. */
  65148. _this.excludedMeshes = new Array();
  65149. /**
  65150. * Controls the overall intensity of the post-process
  65151. * @type {number}
  65152. */
  65153. _this.exposure = 0.3;
  65154. /**
  65155. * Dissipates each sample's contribution in range [0, 1]
  65156. * @type {number}
  65157. */
  65158. _this.decay = 0.96815;
  65159. /**
  65160. * Controls the overall intensity of each sample
  65161. * @type {number}
  65162. */
  65163. _this.weight = 0.58767;
  65164. /**
  65165. * Controls the density of each sample
  65166. * @type {number}
  65167. */
  65168. _this.density = 0.926;
  65169. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  65170. engine = scene.getEngine();
  65171. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  65172. // Configure mesh
  65173. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  65174. // Configure
  65175. _this._createPass(scene, ratio.passRatio || ratio);
  65176. _this.onActivate = function (camera) {
  65177. if (!_this.isSupported) {
  65178. _this.dispose(camera);
  65179. }
  65180. _this.onActivate = null;
  65181. };
  65182. _this.onApplyObservable.add(function (effect) {
  65183. _this._updateMeshScreenCoordinates(scene);
  65184. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  65185. effect.setFloat("exposure", _this.exposure);
  65186. effect.setFloat("decay", _this.decay);
  65187. effect.setFloat("weight", _this.weight);
  65188. effect.setFloat("density", _this.density);
  65189. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  65190. });
  65191. return _this;
  65192. }
  65193. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  65194. get: function () {
  65195. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65196. return false;
  65197. },
  65198. set: function (useDiffuseColor) {
  65199. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65200. },
  65201. enumerable: true,
  65202. configurable: true
  65203. });
  65204. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  65205. return "VolumetricLightScatteringPostProcess";
  65206. };
  65207. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  65208. var mesh = subMesh.getMesh();
  65209. // Render this.mesh as default
  65210. if (mesh === this.mesh && mesh.material) {
  65211. return mesh.material.isReady(mesh);
  65212. }
  65213. var defines = [];
  65214. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65215. var material = subMesh.getMaterial();
  65216. // Alpha test
  65217. if (material) {
  65218. if (material.needAlphaTesting()) {
  65219. defines.push("#define ALPHATEST");
  65220. }
  65221. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65222. attribs.push(BABYLON.VertexBuffer.UVKind);
  65223. defines.push("#define UV1");
  65224. }
  65225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65226. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65227. defines.push("#define UV2");
  65228. }
  65229. }
  65230. // Bones
  65231. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65232. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65233. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65234. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65235. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  65236. }
  65237. else {
  65238. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65239. }
  65240. // Instances
  65241. if (useInstances) {
  65242. defines.push("#define INSTANCES");
  65243. attribs.push("world0");
  65244. attribs.push("world1");
  65245. attribs.push("world2");
  65246. attribs.push("world3");
  65247. }
  65248. // Get correct effect
  65249. var join = defines.join("\n");
  65250. if (this._cachedDefines !== join) {
  65251. this._cachedDefines = join;
  65252. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  65253. }
  65254. return this._volumetricLightScatteringPass.isReady();
  65255. };
  65256. /**
  65257. * Sets the new light position for light scattering effect
  65258. * @param {BABYLON.Vector3} The new custom light position
  65259. */
  65260. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  65261. this.customMeshPosition = position;
  65262. };
  65263. /**
  65264. * Returns the light position for light scattering effect
  65265. * @return {BABYLON.Vector3} The custom light position
  65266. */
  65267. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  65268. return this.customMeshPosition;
  65269. };
  65270. /**
  65271. * Disposes the internal assets and detaches the post-process from the camera
  65272. */
  65273. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  65274. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  65275. if (rttIndex !== -1) {
  65276. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  65277. }
  65278. this._volumetricLightScatteringRTT.dispose();
  65279. _super.prototype.dispose.call(this, camera);
  65280. };
  65281. /**
  65282. * Returns the render target texture used by the post-process
  65283. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  65284. */
  65285. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  65286. return this._volumetricLightScatteringRTT;
  65287. };
  65288. // Private methods
  65289. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  65290. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  65291. return true;
  65292. }
  65293. return false;
  65294. };
  65295. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  65296. var _this = this;
  65297. var engine = scene.getEngine();
  65298. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65299. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65300. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65301. this._volumetricLightScatteringRTT.renderList = null;
  65302. this._volumetricLightScatteringRTT.renderParticles = false;
  65303. var camera = this.getCamera();
  65304. if (camera) {
  65305. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65306. }
  65307. else {
  65308. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65309. }
  65310. // Custom render function for submeshes
  65311. var renderSubMesh = function (subMesh) {
  65312. var mesh = subMesh.getRenderingMesh();
  65313. if (_this._meshExcluded(mesh)) {
  65314. return;
  65315. }
  65316. var material = subMesh.getMaterial();
  65317. if (!material) {
  65318. return;
  65319. }
  65320. var scene = mesh.getScene();
  65321. var engine = scene.getEngine();
  65322. // Culling
  65323. engine.setState(material.backFaceCulling);
  65324. // Managing instances
  65325. var batch = mesh._getInstancesRenderList(subMesh._id);
  65326. if (batch.mustReturn) {
  65327. return;
  65328. }
  65329. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65330. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  65331. var effect = _this._volumetricLightScatteringPass;
  65332. if (mesh === _this.mesh) {
  65333. if (subMesh.effect) {
  65334. effect = subMesh.effect;
  65335. }
  65336. else {
  65337. effect = material.getEffect();
  65338. }
  65339. }
  65340. engine.enableEffect(effect);
  65341. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  65342. if (mesh === _this.mesh) {
  65343. material.bind(mesh.getWorldMatrix(), mesh);
  65344. }
  65345. else {
  65346. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  65347. // Alpha test
  65348. if (material && material.needAlphaTesting()) {
  65349. var alphaTexture = material.getAlphaTestTexture();
  65350. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  65351. if (alphaTexture) {
  65352. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65353. }
  65354. }
  65355. // Bones
  65356. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65357. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65358. }
  65359. }
  65360. // Draw
  65361. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  65362. }
  65363. };
  65364. // Render target texture callbacks
  65365. var savedSceneClearColor;
  65366. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  65367. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  65368. savedSceneClearColor = scene.clearColor;
  65369. scene.clearColor = sceneClearColor;
  65370. });
  65371. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  65372. scene.clearColor = savedSceneClearColor;
  65373. });
  65374. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65375. var engine = scene.getEngine();
  65376. var index;
  65377. if (depthOnlySubMeshes.length) {
  65378. engine.setColorWrite(false);
  65379. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65380. renderSubMesh(depthOnlySubMeshes.data[index]);
  65381. }
  65382. engine.setColorWrite(true);
  65383. }
  65384. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65385. renderSubMesh(opaqueSubMeshes.data[index]);
  65386. }
  65387. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65388. renderSubMesh(alphaTestSubMeshes.data[index]);
  65389. }
  65390. if (transparentSubMeshes.length) {
  65391. // Sort sub meshes
  65392. for (index = 0; index < transparentSubMeshes.length; index++) {
  65393. var submesh = transparentSubMeshes.data[index];
  65394. var boundingInfo = submesh.getBoundingInfo();
  65395. if (boundingInfo && scene.activeCamera) {
  65396. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  65397. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  65398. }
  65399. }
  65400. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  65401. sortedArray.sort(function (a, b) {
  65402. // Alpha index first
  65403. if (a._alphaIndex > b._alphaIndex) {
  65404. return 1;
  65405. }
  65406. if (a._alphaIndex < b._alphaIndex) {
  65407. return -1;
  65408. }
  65409. // Then distance to camera
  65410. if (a._distanceToCamera < b._distanceToCamera) {
  65411. return 1;
  65412. }
  65413. if (a._distanceToCamera > b._distanceToCamera) {
  65414. return -1;
  65415. }
  65416. return 0;
  65417. });
  65418. // Render sub meshes
  65419. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65420. for (index = 0; index < sortedArray.length; index++) {
  65421. renderSubMesh(sortedArray[index]);
  65422. }
  65423. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65424. }
  65425. };
  65426. };
  65427. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  65428. var transform = scene.getTransformMatrix();
  65429. var meshPosition;
  65430. if (this.useCustomMeshPosition) {
  65431. meshPosition = this.customMeshPosition;
  65432. }
  65433. else if (this.attachedNode) {
  65434. meshPosition = this.attachedNode.position;
  65435. }
  65436. else {
  65437. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  65438. }
  65439. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  65440. this._screenCoordinates.x = pos.x / this._viewPort.width;
  65441. this._screenCoordinates.y = pos.y / this._viewPort.height;
  65442. if (this.invert)
  65443. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  65444. };
  65445. // Static methods
  65446. /**
  65447. * Creates a default mesh for the Volumeric Light Scattering post-process
  65448. * @param {string} The mesh name
  65449. * @param {BABYLON.Scene} The scene where to create the mesh
  65450. * @return {BABYLON.Mesh} the default mesh
  65451. */
  65452. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  65453. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  65454. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  65455. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  65456. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  65457. mesh.material = material;
  65458. return mesh;
  65459. };
  65460. __decorate([
  65461. BABYLON.serializeAsVector3()
  65462. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  65463. __decorate([
  65464. BABYLON.serialize()
  65465. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  65466. __decorate([
  65467. BABYLON.serialize()
  65468. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  65469. __decorate([
  65470. BABYLON.serializeAsMeshReference()
  65471. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  65472. __decorate([
  65473. BABYLON.serialize()
  65474. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  65475. __decorate([
  65476. BABYLON.serialize()
  65477. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  65478. __decorate([
  65479. BABYLON.serialize()
  65480. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  65481. __decorate([
  65482. BABYLON.serialize()
  65483. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  65484. __decorate([
  65485. BABYLON.serialize()
  65486. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  65487. return VolumetricLightScatteringPostProcess;
  65488. }(BABYLON.PostProcess));
  65489. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  65490. })(BABYLON || (BABYLON = {}));
  65491. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  65492. //
  65493. // This post-process allows the modification of rendered colors by using
  65494. // a 'look-up table' (LUT). This effect is also called Color Grading.
  65495. //
  65496. // The object needs to be provided an url to a texture containing the color
  65497. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  65498. // Use an image editing software to tweak the LUT to match your needs.
  65499. //
  65500. // For an example of a color LUT, see here:
  65501. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  65502. // For explanations on color grading, see here:
  65503. // http://udn.epicgames.com/Three/ColorGrading.html
  65504. //
  65505. var BABYLON;
  65506. (function (BABYLON) {
  65507. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  65508. __extends(ColorCorrectionPostProcess, _super);
  65509. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  65510. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  65511. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65512. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  65513. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65514. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65515. _this.onApply = function (effect) {
  65516. effect.setTexture("colorTable", _this._colorTableTexture);
  65517. };
  65518. return _this;
  65519. }
  65520. return ColorCorrectionPostProcess;
  65521. }(BABYLON.PostProcess));
  65522. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  65523. })(BABYLON || (BABYLON = {}));
  65524. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  65525. var BABYLON;
  65526. (function (BABYLON) {
  65527. var TonemappingOperator;
  65528. (function (TonemappingOperator) {
  65529. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  65530. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  65531. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  65532. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  65533. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  65534. ;
  65535. var TonemapPostProcess = /** @class */ (function (_super) {
  65536. __extends(TonemapPostProcess, _super);
  65537. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  65538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65539. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65540. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  65541. _this._operator = _operator;
  65542. _this.exposureAdjustment = exposureAdjustment;
  65543. var defines = "#define ";
  65544. if (_this._operator === TonemappingOperator.Hable)
  65545. defines += "HABLE_TONEMAPPING";
  65546. else if (_this._operator === TonemappingOperator.Reinhard)
  65547. defines += "REINHARD_TONEMAPPING";
  65548. else if (_this._operator === TonemappingOperator.HejiDawson)
  65549. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  65550. else if (_this._operator === TonemappingOperator.Photographic)
  65551. defines += "PHOTOGRAPHIC_TONEMAPPING";
  65552. //sadly a second call to create the effect.
  65553. _this.updateEffect(defines);
  65554. _this.onApply = function (effect) {
  65555. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  65556. };
  65557. return _this;
  65558. }
  65559. return TonemapPostProcess;
  65560. }(BABYLON.PostProcess));
  65561. BABYLON.TonemapPostProcess = TonemapPostProcess;
  65562. })(BABYLON || (BABYLON = {}));
  65563. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  65564. var BABYLON;
  65565. (function (BABYLON) {
  65566. var DisplayPassPostProcess = /** @class */ (function (_super) {
  65567. __extends(DisplayPassPostProcess, _super);
  65568. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  65569. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  65570. }
  65571. return DisplayPassPostProcess;
  65572. }(BABYLON.PostProcess));
  65573. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  65574. })(BABYLON || (BABYLON = {}));
  65575. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  65576. var BABYLON;
  65577. (function (BABYLON) {
  65578. var HighlightsPostProcess = /** @class */ (function (_super) {
  65579. __extends(HighlightsPostProcess, _super);
  65580. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65581. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65582. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65583. }
  65584. return HighlightsPostProcess;
  65585. }(BABYLON.PostProcess));
  65586. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  65587. })(BABYLON || (BABYLON = {}));
  65588. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  65589. var BABYLON;
  65590. (function (BABYLON) {
  65591. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  65592. __extends(ImageProcessingPostProcess, _super);
  65593. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  65594. if (camera === void 0) { camera = null; }
  65595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65596. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  65597. _this._fromLinearSpace = true;
  65598. /**
  65599. * Defines cache preventing GC.
  65600. */
  65601. _this._defines = {
  65602. IMAGEPROCESSING: false,
  65603. VIGNETTE: false,
  65604. VIGNETTEBLENDMODEMULTIPLY: false,
  65605. VIGNETTEBLENDMODEOPAQUE: false,
  65606. TONEMAPPING: false,
  65607. CONTRAST: false,
  65608. COLORCURVES: false,
  65609. COLORGRADING: false,
  65610. COLORGRADING3D: false,
  65611. FROMLINEARSPACE: false,
  65612. SAMPLER3DGREENDEPTH: false,
  65613. SAMPLER3DBGRMAP: false,
  65614. IMAGEPROCESSINGPOSTPROCESS: false,
  65615. EXPOSURE: false,
  65616. };
  65617. // Setup the configuration as forced by the constructor. This would then not force the
  65618. // scene materials output in linear space and let untouched the default forward pass.
  65619. if (imageProcessingConfiguration) {
  65620. imageProcessingConfiguration.applyByPostProcess = true;
  65621. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  65622. // This will cause the shader to be compiled
  65623. _this.fromLinearSpace = false;
  65624. }
  65625. else {
  65626. _this._attachImageProcessingConfiguration(null, true);
  65627. _this.imageProcessingConfiguration.applyByPostProcess = true;
  65628. }
  65629. _this.onApply = function (effect) {
  65630. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  65631. };
  65632. return _this;
  65633. }
  65634. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  65635. /**
  65636. * Gets the image processing configuration used either in this material.
  65637. */
  65638. get: function () {
  65639. return this._imageProcessingConfiguration;
  65640. },
  65641. /**
  65642. * Sets the Default image processing configuration used either in the this material.
  65643. *
  65644. * If sets to null, the scene one is in use.
  65645. */
  65646. set: function (value) {
  65647. this._attachImageProcessingConfiguration(value);
  65648. },
  65649. enumerable: true,
  65650. configurable: true
  65651. });
  65652. /**
  65653. * Attaches a new image processing configuration to the PBR Material.
  65654. * @param configuration
  65655. */
  65656. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  65657. var _this = this;
  65658. if (doNotBuild === void 0) { doNotBuild = false; }
  65659. if (configuration === this._imageProcessingConfiguration) {
  65660. return;
  65661. }
  65662. // Detaches observer.
  65663. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65664. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65665. }
  65666. // Pick the scene configuration if needed.
  65667. if (!configuration) {
  65668. var scene = null;
  65669. var engine = this.getEngine();
  65670. var camera = this.getCamera();
  65671. if (camera) {
  65672. scene = camera.getScene();
  65673. }
  65674. else if (engine && engine.scenes) {
  65675. var scenes = engine.scenes;
  65676. scene = scenes[scenes.length - 1];
  65677. }
  65678. else {
  65679. scene = BABYLON.Engine.LastCreatedScene;
  65680. }
  65681. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  65682. }
  65683. else {
  65684. this._imageProcessingConfiguration = configuration;
  65685. }
  65686. // Attaches observer.
  65687. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  65688. _this._updateParameters();
  65689. });
  65690. // Ensure the effect will be rebuilt.
  65691. if (!doNotBuild) {
  65692. this._updateParameters();
  65693. }
  65694. };
  65695. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  65696. /**
  65697. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65698. */
  65699. get: function () {
  65700. return this.imageProcessingConfiguration.colorCurves;
  65701. },
  65702. /**
  65703. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65704. */
  65705. set: function (value) {
  65706. this.imageProcessingConfiguration.colorCurves = value;
  65707. },
  65708. enumerable: true,
  65709. configurable: true
  65710. });
  65711. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  65712. /**
  65713. * Gets wether the color curves effect is enabled.
  65714. */
  65715. get: function () {
  65716. return this.imageProcessingConfiguration.colorCurvesEnabled;
  65717. },
  65718. /**
  65719. * Sets wether the color curves effect is enabled.
  65720. */
  65721. set: function (value) {
  65722. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  65723. },
  65724. enumerable: true,
  65725. configurable: true
  65726. });
  65727. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  65728. /**
  65729. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65730. */
  65731. get: function () {
  65732. return this.imageProcessingConfiguration.colorGradingTexture;
  65733. },
  65734. /**
  65735. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65736. */
  65737. set: function (value) {
  65738. this.imageProcessingConfiguration.colorGradingTexture = value;
  65739. },
  65740. enumerable: true,
  65741. configurable: true
  65742. });
  65743. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  65744. /**
  65745. * Gets wether the color grading effect is enabled.
  65746. */
  65747. get: function () {
  65748. return this.imageProcessingConfiguration.colorGradingEnabled;
  65749. },
  65750. /**
  65751. * Gets wether the color grading effect is enabled.
  65752. */
  65753. set: function (value) {
  65754. this.imageProcessingConfiguration.colorGradingEnabled = value;
  65755. },
  65756. enumerable: true,
  65757. configurable: true
  65758. });
  65759. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  65760. /**
  65761. * Gets exposure used in the effect.
  65762. */
  65763. get: function () {
  65764. return this.imageProcessingConfiguration.exposure;
  65765. },
  65766. /**
  65767. * Sets exposure used in the effect.
  65768. */
  65769. set: function (value) {
  65770. this.imageProcessingConfiguration.exposure = value;
  65771. },
  65772. enumerable: true,
  65773. configurable: true
  65774. });
  65775. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  65776. /**
  65777. * Gets wether tonemapping is enabled or not.
  65778. */
  65779. get: function () {
  65780. return this._imageProcessingConfiguration.toneMappingEnabled;
  65781. },
  65782. /**
  65783. * Sets wether tonemapping is enabled or not
  65784. */
  65785. set: function (value) {
  65786. this._imageProcessingConfiguration.toneMappingEnabled = value;
  65787. },
  65788. enumerable: true,
  65789. configurable: true
  65790. });
  65791. ;
  65792. ;
  65793. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  65794. /**
  65795. * Gets contrast used in the effect.
  65796. */
  65797. get: function () {
  65798. return this.imageProcessingConfiguration.contrast;
  65799. },
  65800. /**
  65801. * Sets contrast used in the effect.
  65802. */
  65803. set: function (value) {
  65804. this.imageProcessingConfiguration.contrast = value;
  65805. },
  65806. enumerable: true,
  65807. configurable: true
  65808. });
  65809. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  65810. /**
  65811. * Gets Vignette stretch size.
  65812. */
  65813. get: function () {
  65814. return this.imageProcessingConfiguration.vignetteStretch;
  65815. },
  65816. /**
  65817. * Sets Vignette stretch size.
  65818. */
  65819. set: function (value) {
  65820. this.imageProcessingConfiguration.vignetteStretch = value;
  65821. },
  65822. enumerable: true,
  65823. configurable: true
  65824. });
  65825. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  65826. /**
  65827. * Gets Vignette centre X Offset.
  65828. */
  65829. get: function () {
  65830. return this.imageProcessingConfiguration.vignetteCentreX;
  65831. },
  65832. /**
  65833. * Sets Vignette centre X Offset.
  65834. */
  65835. set: function (value) {
  65836. this.imageProcessingConfiguration.vignetteCentreX = value;
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  65842. /**
  65843. * Gets Vignette centre Y Offset.
  65844. */
  65845. get: function () {
  65846. return this.imageProcessingConfiguration.vignetteCentreY;
  65847. },
  65848. /**
  65849. * Sets Vignette centre Y Offset.
  65850. */
  65851. set: function (value) {
  65852. this.imageProcessingConfiguration.vignetteCentreY = value;
  65853. },
  65854. enumerable: true,
  65855. configurable: true
  65856. });
  65857. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  65858. /**
  65859. * Gets Vignette weight or intensity of the vignette effect.
  65860. */
  65861. get: function () {
  65862. return this.imageProcessingConfiguration.vignetteWeight;
  65863. },
  65864. /**
  65865. * Sets Vignette weight or intensity of the vignette effect.
  65866. */
  65867. set: function (value) {
  65868. this.imageProcessingConfiguration.vignetteWeight = value;
  65869. },
  65870. enumerable: true,
  65871. configurable: true
  65872. });
  65873. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  65874. /**
  65875. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65876. * if vignetteEnabled is set to true.
  65877. */
  65878. get: function () {
  65879. return this.imageProcessingConfiguration.vignetteColor;
  65880. },
  65881. /**
  65882. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65883. * if vignetteEnabled is set to true.
  65884. */
  65885. set: function (value) {
  65886. this.imageProcessingConfiguration.vignetteColor = value;
  65887. },
  65888. enumerable: true,
  65889. configurable: true
  65890. });
  65891. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  65892. /**
  65893. * Gets Camera field of view used by the Vignette effect.
  65894. */
  65895. get: function () {
  65896. return this.imageProcessingConfiguration.vignetteCameraFov;
  65897. },
  65898. /**
  65899. * Sets Camera field of view used by the Vignette effect.
  65900. */
  65901. set: function (value) {
  65902. this.imageProcessingConfiguration.vignetteCameraFov = value;
  65903. },
  65904. enumerable: true,
  65905. configurable: true
  65906. });
  65907. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  65908. /**
  65909. * Gets the vignette blend mode allowing different kind of effect.
  65910. */
  65911. get: function () {
  65912. return this.imageProcessingConfiguration.vignetteBlendMode;
  65913. },
  65914. /**
  65915. * Sets the vignette blend mode allowing different kind of effect.
  65916. */
  65917. set: function (value) {
  65918. this.imageProcessingConfiguration.vignetteBlendMode = value;
  65919. },
  65920. enumerable: true,
  65921. configurable: true
  65922. });
  65923. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  65924. /**
  65925. * Gets wether the vignette effect is enabled.
  65926. */
  65927. get: function () {
  65928. return this.imageProcessingConfiguration.vignetteEnabled;
  65929. },
  65930. /**
  65931. * Sets wether the vignette effect is enabled.
  65932. */
  65933. set: function (value) {
  65934. this.imageProcessingConfiguration.vignetteEnabled = value;
  65935. },
  65936. enumerable: true,
  65937. configurable: true
  65938. });
  65939. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  65940. /**
  65941. * Gets wether the input of the processing is in Gamma or Linear Space.
  65942. */
  65943. get: function () {
  65944. return this._fromLinearSpace;
  65945. },
  65946. /**
  65947. * Sets wether the input of the processing is in Gamma or Linear Space.
  65948. */
  65949. set: function (value) {
  65950. if (this._fromLinearSpace === value) {
  65951. return;
  65952. }
  65953. this._fromLinearSpace = value;
  65954. this._updateParameters();
  65955. },
  65956. enumerable: true,
  65957. configurable: true
  65958. });
  65959. ImageProcessingPostProcess.prototype.getClassName = function () {
  65960. return "ImageProcessingPostProcess";
  65961. };
  65962. ImageProcessingPostProcess.prototype._updateParameters = function () {
  65963. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  65964. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  65965. var defines = "";
  65966. for (var define in this._defines) {
  65967. if (this._defines[define]) {
  65968. defines += "#define " + define + ";\r\n";
  65969. }
  65970. }
  65971. var samplers = ["textureSampler"];
  65972. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  65973. var uniforms = ["scale"];
  65974. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  65975. this.updateEffect(defines, uniforms, samplers);
  65976. };
  65977. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  65978. _super.prototype.dispose.call(this, camera);
  65979. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65980. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65981. }
  65982. this.imageProcessingConfiguration.applyByPostProcess = false;
  65983. };
  65984. __decorate([
  65985. BABYLON.serialize()
  65986. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  65987. return ImageProcessingPostProcess;
  65988. }(BABYLON.PostProcess));
  65989. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  65990. })(BABYLON || (BABYLON = {}));
  65991. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  65992. var BABYLON;
  65993. (function (BABYLON) {
  65994. var BlurPostProcess = /** @class */ (function (_super) {
  65995. __extends(BlurPostProcess, _super);
  65996. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  65997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65998. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65999. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  66000. _this.direction = direction;
  66001. _this._packedFloat = false;
  66002. _this._staticDefines = "";
  66003. _this.onApplyObservable.add(function (effect) {
  66004. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  66005. });
  66006. _this.kernel = kernel;
  66007. return _this;
  66008. }
  66009. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  66010. /**
  66011. * Gets the length in pixels of the blur sample region
  66012. */
  66013. get: function () {
  66014. return this._idealKernel;
  66015. },
  66016. /**
  66017. * Sets the length in pixels of the blur sample region
  66018. */
  66019. set: function (v) {
  66020. if (this._idealKernel === v) {
  66021. return;
  66022. }
  66023. v = Math.max(v, 1);
  66024. this._idealKernel = v;
  66025. this._kernel = this._nearestBestKernel(v);
  66026. this._updateParameters();
  66027. },
  66028. enumerable: true,
  66029. configurable: true
  66030. });
  66031. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  66032. /**
  66033. * Gets wether or not the blur is unpacking/repacking floats
  66034. */
  66035. get: function () {
  66036. return this._packedFloat;
  66037. },
  66038. /**
  66039. * Sets wether or not the blur needs to unpack/repack floats
  66040. */
  66041. set: function (v) {
  66042. if (this._packedFloat === v) {
  66043. return;
  66044. }
  66045. this._packedFloat = v;
  66046. this._updateParameters();
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. BlurPostProcess.prototype._updateParameters = function () {
  66052. // Generate sampling offsets and weights
  66053. var N = this._kernel;
  66054. var centerIndex = (N - 1) / 2;
  66055. // Generate Gaussian sampling weights over kernel
  66056. var offsets = [];
  66057. var weights = [];
  66058. var totalWeight = 0;
  66059. for (var i = 0; i < N; i++) {
  66060. var u = i / (N - 1);
  66061. var w = this._gaussianWeight(u * 2.0 - 1);
  66062. offsets[i] = (i - centerIndex);
  66063. weights[i] = w;
  66064. totalWeight += w;
  66065. }
  66066. // Normalize weights
  66067. for (var i = 0; i < weights.length; i++) {
  66068. weights[i] /= totalWeight;
  66069. }
  66070. // Optimize: combine samples to take advantage of hardware linear sampling
  66071. // Walk from left to center, combining pairs (symmetrically)
  66072. var linearSamplingWeights = [];
  66073. var linearSamplingOffsets = [];
  66074. var linearSamplingMap = [];
  66075. for (var i = 0; i <= centerIndex; i += 2) {
  66076. var j = Math.min(i + 1, Math.floor(centerIndex));
  66077. var singleCenterSample = i === j;
  66078. if (singleCenterSample) {
  66079. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66080. }
  66081. else {
  66082. var sharedCell = j === centerIndex;
  66083. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  66084. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  66085. if (offsetLinear === 0) {
  66086. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66087. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  66088. }
  66089. else {
  66090. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  66091. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  66092. }
  66093. }
  66094. }
  66095. for (var i = 0; i < linearSamplingMap.length; i++) {
  66096. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  66097. linearSamplingWeights[i] = linearSamplingMap[i].w;
  66098. }
  66099. // Replace with optimized
  66100. offsets = linearSamplingOffsets;
  66101. weights = linearSamplingWeights;
  66102. // Generate shaders
  66103. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  66104. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  66105. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  66106. var defines = "";
  66107. defines += this._staticDefines;
  66108. for (var i = 0; i < varyingCount; i++) {
  66109. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  66110. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  66111. }
  66112. var depCount = 0;
  66113. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  66114. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  66115. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  66116. depCount++;
  66117. }
  66118. if (this.packedFloat) {
  66119. defines += "#define PACKEDFLOAT 1";
  66120. }
  66121. this.updateEffect(defines, null, null, {
  66122. varyingCount: varyingCount,
  66123. depCount: depCount
  66124. });
  66125. };
  66126. /**
  66127. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  66128. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  66129. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  66130. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  66131. * The gaps between physical kernels are compensated for in the weighting of the samples
  66132. * @param idealKernel Ideal blur kernel.
  66133. * @return Nearest best kernel.
  66134. */
  66135. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  66136. var v = Math.round(idealKernel);
  66137. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  66138. var k = _a[_i];
  66139. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  66140. return Math.max(k, 3);
  66141. }
  66142. }
  66143. return Math.max(v, 3);
  66144. };
  66145. /**
  66146. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  66147. * @param x The point on the Gaussian distribution to sample.
  66148. * @return the value of the Gaussian function at x.
  66149. */
  66150. BlurPostProcess.prototype._gaussianWeight = function (x) {
  66151. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  66152. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  66153. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  66154. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  66155. // truncated at around 1.3% of peak strength.
  66156. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  66157. var sigma = (1 / 3);
  66158. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  66159. var exponent = -((x * x) / (2.0 * sigma * sigma));
  66160. var weight = (1.0 / denominator) * Math.exp(exponent);
  66161. return weight;
  66162. };
  66163. /**
  66164. * Generates a string that can be used as a floating point number in GLSL.
  66165. * @param x Value to print.
  66166. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  66167. * @return GLSL float string.
  66168. */
  66169. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  66170. if (decimalFigures === void 0) { decimalFigures = 8; }
  66171. return x.toFixed(decimalFigures).replace(/0+$/, '');
  66172. };
  66173. return BlurPostProcess;
  66174. }(BABYLON.PostProcess));
  66175. BABYLON.BlurPostProcess = BlurPostProcess;
  66176. })(BABYLON || (BABYLON = {}));
  66177. //# sourceMappingURL=babylon.blurPostProcess.js.map
  66178. var BABYLON;
  66179. (function (BABYLON) {
  66180. var Bone = /** @class */ (function (_super) {
  66181. __extends(Bone, _super);
  66182. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  66183. if (parentBone === void 0) { parentBone = null; }
  66184. if (localMatrix === void 0) { localMatrix = null; }
  66185. if (restPose === void 0) { restPose = null; }
  66186. if (baseMatrix === void 0) { baseMatrix = null; }
  66187. if (index === void 0) { index = null; }
  66188. var _this = _super.call(this, name, skeleton.getScene()) || this;
  66189. _this.name = name;
  66190. _this.children = new Array();
  66191. _this.animations = new Array();
  66192. // Set this value to map this bone to a different index in the transform matrices.
  66193. // Set this value to -1 to exclude the bone from the transform matrices.
  66194. _this._index = null;
  66195. _this._worldTransform = new BABYLON.Matrix();
  66196. _this._absoluteTransform = new BABYLON.Matrix();
  66197. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  66198. _this._scaleMatrix = BABYLON.Matrix.Identity();
  66199. _this._scaleVector = BABYLON.Vector3.One();
  66200. _this._negateScaleChildren = BABYLON.Vector3.One();
  66201. _this._scalingDeterminant = 1;
  66202. _this._skeleton = skeleton;
  66203. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  66204. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  66205. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  66206. _this._index = index;
  66207. skeleton.bones.push(_this);
  66208. _this.setParent(parentBone, false);
  66209. _this._updateDifferenceMatrix();
  66210. return _this;
  66211. }
  66212. Object.defineProperty(Bone.prototype, "_matrix", {
  66213. get: function () {
  66214. return this._localMatrix;
  66215. },
  66216. set: function (val) {
  66217. if (this._localMatrix) {
  66218. this._localMatrix.copyFrom(val);
  66219. }
  66220. else {
  66221. this._localMatrix = val;
  66222. }
  66223. },
  66224. enumerable: true,
  66225. configurable: true
  66226. });
  66227. // Members
  66228. Bone.prototype.getSkeleton = function () {
  66229. return this._skeleton;
  66230. };
  66231. Bone.prototype.getParent = function () {
  66232. return this._parent;
  66233. };
  66234. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  66235. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66236. if (this._parent === parent) {
  66237. return;
  66238. }
  66239. if (this._parent) {
  66240. var index = this._parent.children.indexOf(this);
  66241. if (index !== -1) {
  66242. this._parent.children.splice(index, 1);
  66243. }
  66244. }
  66245. this._parent = parent;
  66246. if (this._parent) {
  66247. this._parent.children.push(this);
  66248. }
  66249. if (updateDifferenceMatrix) {
  66250. this._updateDifferenceMatrix();
  66251. }
  66252. };
  66253. Bone.prototype.getLocalMatrix = function () {
  66254. return this._localMatrix;
  66255. };
  66256. Bone.prototype.getBaseMatrix = function () {
  66257. return this._baseMatrix;
  66258. };
  66259. Bone.prototype.getRestPose = function () {
  66260. return this._restPose;
  66261. };
  66262. Bone.prototype.returnToRest = function () {
  66263. this.updateMatrix(this._restPose.clone());
  66264. };
  66265. Bone.prototype.getWorldMatrix = function () {
  66266. return this._worldTransform;
  66267. };
  66268. Bone.prototype.getInvertedAbsoluteTransform = function () {
  66269. return this._invertedAbsoluteTransform;
  66270. };
  66271. Bone.prototype.getAbsoluteTransform = function () {
  66272. return this._absoluteTransform;
  66273. };
  66274. Object.defineProperty(Bone.prototype, "position", {
  66275. // Properties (matches AbstractMesh properties)
  66276. get: function () {
  66277. return this.getPosition();
  66278. },
  66279. set: function (newPosition) {
  66280. this.setPosition(newPosition);
  66281. },
  66282. enumerable: true,
  66283. configurable: true
  66284. });
  66285. Object.defineProperty(Bone.prototype, "rotation", {
  66286. get: function () {
  66287. return this.getRotation();
  66288. },
  66289. set: function (newRotation) {
  66290. this.setRotation(newRotation);
  66291. },
  66292. enumerable: true,
  66293. configurable: true
  66294. });
  66295. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  66296. get: function () {
  66297. return this.getRotationQuaternion();
  66298. },
  66299. set: function (newRotation) {
  66300. this.setRotationQuaternion(newRotation);
  66301. },
  66302. enumerable: true,
  66303. configurable: true
  66304. });
  66305. Object.defineProperty(Bone.prototype, "scaling", {
  66306. get: function () {
  66307. return this.getScale();
  66308. },
  66309. set: function (newScaling) {
  66310. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  66311. },
  66312. enumerable: true,
  66313. configurable: true
  66314. });
  66315. // Methods
  66316. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  66317. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66318. this._baseMatrix = matrix.clone();
  66319. this._localMatrix = matrix.clone();
  66320. this._skeleton._markAsDirty();
  66321. if (updateDifferenceMatrix) {
  66322. this._updateDifferenceMatrix();
  66323. }
  66324. };
  66325. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  66326. if (!rootMatrix) {
  66327. rootMatrix = this._baseMatrix;
  66328. }
  66329. if (this._parent) {
  66330. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66331. }
  66332. else {
  66333. this._absoluteTransform.copyFrom(rootMatrix);
  66334. }
  66335. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  66336. for (var index = 0; index < this.children.length; index++) {
  66337. this.children[index]._updateDifferenceMatrix();
  66338. }
  66339. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  66340. };
  66341. Bone.prototype.markAsDirty = function () {
  66342. this._currentRenderId++;
  66343. this._skeleton._markAsDirty();
  66344. };
  66345. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  66346. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66347. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  66348. // all animation may be coming from a library skeleton, so may need to create animation
  66349. if (this.animations.length === 0) {
  66350. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  66351. this.animations[0].setKeys([]);
  66352. }
  66353. // get animation info / verify there is such a range from the source bone
  66354. var sourceRange = source.animations[0].getRange(rangeName);
  66355. if (!sourceRange) {
  66356. return false;
  66357. }
  66358. var from = sourceRange.from;
  66359. var to = sourceRange.to;
  66360. var sourceKeys = source.animations[0].getKeys();
  66361. // rescaling prep
  66362. var sourceBoneLength = source.length;
  66363. var sourceParent = source.getParent();
  66364. var parent = this.getParent();
  66365. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  66366. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  66367. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  66368. var destKeys = this.animations[0].getKeys();
  66369. // loop vars declaration
  66370. var orig;
  66371. var origTranslation;
  66372. var mat;
  66373. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  66374. orig = sourceKeys[key];
  66375. if (orig.frame >= from && orig.frame <= to) {
  66376. if (rescaleAsRequired) {
  66377. mat = orig.value.clone();
  66378. // scale based on parent ratio, when bone has parent
  66379. if (parentScalingReqd) {
  66380. origTranslation = mat.getTranslation();
  66381. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  66382. // scale based on skeleton dimension ratio when root bone, and value is passed
  66383. }
  66384. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  66385. origTranslation = mat.getTranslation();
  66386. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  66387. // use original when root bone, and no data for skelDimensionsRatio
  66388. }
  66389. else {
  66390. mat = orig.value;
  66391. }
  66392. }
  66393. else {
  66394. mat = orig.value;
  66395. }
  66396. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  66397. }
  66398. }
  66399. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  66400. return true;
  66401. };
  66402. /**
  66403. * Translate the bone in local or world space.
  66404. * @param vec The amount to translate the bone.
  66405. * @param space The space that the translation is in.
  66406. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66407. */
  66408. Bone.prototype.translate = function (vec, space, mesh) {
  66409. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66410. var lm = this.getLocalMatrix();
  66411. if (space == BABYLON.Space.LOCAL) {
  66412. lm.m[12] += vec.x;
  66413. lm.m[13] += vec.y;
  66414. lm.m[14] += vec.z;
  66415. }
  66416. else {
  66417. var wm = null;
  66418. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66419. if (mesh) {
  66420. wm = mesh.getWorldMatrix();
  66421. }
  66422. this._skeleton.computeAbsoluteTransforms();
  66423. var tmat = Bone._tmpMats[0];
  66424. var tvec = Bone._tmpVecs[0];
  66425. if (this._parent) {
  66426. if (mesh && wm) {
  66427. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66428. tmat.multiplyToRef(wm, tmat);
  66429. }
  66430. else {
  66431. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66432. }
  66433. }
  66434. tmat.m[12] = 0;
  66435. tmat.m[13] = 0;
  66436. tmat.m[14] = 0;
  66437. tmat.invert();
  66438. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  66439. lm.m[12] += tvec.x;
  66440. lm.m[13] += tvec.y;
  66441. lm.m[14] += tvec.z;
  66442. }
  66443. this.markAsDirty();
  66444. };
  66445. /**
  66446. * Set the postion of the bone in local or world space.
  66447. * @param position The position to set the bone.
  66448. * @param space The space that the position is in.
  66449. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66450. */
  66451. Bone.prototype.setPosition = function (position, space, mesh) {
  66452. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66453. var lm = this.getLocalMatrix();
  66454. if (space == BABYLON.Space.LOCAL) {
  66455. lm.m[12] = position.x;
  66456. lm.m[13] = position.y;
  66457. lm.m[14] = position.z;
  66458. }
  66459. else {
  66460. var wm = null;
  66461. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66462. if (mesh) {
  66463. wm = mesh.getWorldMatrix();
  66464. }
  66465. this._skeleton.computeAbsoluteTransforms();
  66466. var tmat = Bone._tmpMats[0];
  66467. var vec = Bone._tmpVecs[0];
  66468. if (this._parent) {
  66469. if (mesh && wm) {
  66470. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66471. tmat.multiplyToRef(wm, tmat);
  66472. }
  66473. else {
  66474. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66475. }
  66476. }
  66477. tmat.invert();
  66478. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  66479. lm.m[12] = vec.x;
  66480. lm.m[13] = vec.y;
  66481. lm.m[14] = vec.z;
  66482. }
  66483. this.markAsDirty();
  66484. };
  66485. /**
  66486. * Set the absolute postion of the bone (world space).
  66487. * @param position The position to set the bone.
  66488. * @param mesh The mesh that this bone is attached to.
  66489. */
  66490. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  66491. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  66492. };
  66493. /**
  66494. * Set the scale of the bone on the x, y and z axes.
  66495. * @param x The scale of the bone on the x axis.
  66496. * @param x The scale of the bone on the y axis.
  66497. * @param z The scale of the bone on the z axis.
  66498. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66499. */
  66500. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  66501. if (scaleChildren === void 0) { scaleChildren = false; }
  66502. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  66503. if (!scaleChildren) {
  66504. this._negateScaleChildren.x = 1 / x;
  66505. this._negateScaleChildren.y = 1 / y;
  66506. this._negateScaleChildren.z = 1 / z;
  66507. }
  66508. this._syncScaleVector();
  66509. }
  66510. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  66511. };
  66512. /**
  66513. * Scale the bone on the x, y and z axes.
  66514. * @param x The amount to scale the bone on the x axis.
  66515. * @param x The amount to scale the bone on the y axis.
  66516. * @param z The amount to scale the bone on the z axis.
  66517. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66518. */
  66519. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  66520. if (scaleChildren === void 0) { scaleChildren = false; }
  66521. var locMat = this.getLocalMatrix();
  66522. var origLocMat = Bone._tmpMats[0];
  66523. origLocMat.copyFrom(locMat);
  66524. var origLocMatInv = Bone._tmpMats[1];
  66525. origLocMatInv.copyFrom(origLocMat);
  66526. origLocMatInv.invert();
  66527. var scaleMat = Bone._tmpMats[2];
  66528. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  66529. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  66530. this._scaleVector.x *= x;
  66531. this._scaleVector.y *= y;
  66532. this._scaleVector.z *= z;
  66533. locMat.multiplyToRef(origLocMatInv, locMat);
  66534. locMat.multiplyToRef(scaleMat, locMat);
  66535. locMat.multiplyToRef(origLocMat, locMat);
  66536. var parent = this.getParent();
  66537. if (parent) {
  66538. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  66539. }
  66540. else {
  66541. this.getAbsoluteTransform().copyFrom(locMat);
  66542. }
  66543. var len = this.children.length;
  66544. scaleMat.invert();
  66545. for (var i = 0; i < len; i++) {
  66546. var child = this.children[i];
  66547. var cm = child.getLocalMatrix();
  66548. cm.multiplyToRef(scaleMat, cm);
  66549. var lm = child.getLocalMatrix();
  66550. lm.m[12] *= x;
  66551. lm.m[13] *= y;
  66552. lm.m[14] *= z;
  66553. }
  66554. this.computeAbsoluteTransforms();
  66555. if (scaleChildren) {
  66556. for (var i = 0; i < len; i++) {
  66557. this.children[i].scale(x, y, z, scaleChildren);
  66558. }
  66559. }
  66560. this.markAsDirty();
  66561. };
  66562. /**
  66563. * Set the yaw, pitch, and roll of the bone in local or world space.
  66564. * @param yaw The rotation of the bone on the y axis.
  66565. * @param pitch The rotation of the bone on the x axis.
  66566. * @param roll The rotation of the bone on the z axis.
  66567. * @param space The space that the axes of rotation are in.
  66568. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66569. */
  66570. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  66571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66572. var rotMat = Bone._tmpMats[0];
  66573. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  66574. var rotMatInv = Bone._tmpMats[1];
  66575. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66576. rotMatInv.multiplyToRef(rotMat, rotMat);
  66577. this._rotateWithMatrix(rotMat, space, mesh);
  66578. };
  66579. /**
  66580. * Rotate the bone on an axis in local or world space.
  66581. * @param axis The axis to rotate the bone on.
  66582. * @param amount The amount to rotate the bone.
  66583. * @param space The space that the axis is in.
  66584. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66585. */
  66586. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  66587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66588. var rmat = Bone._tmpMats[0];
  66589. rmat.m[12] = 0;
  66590. rmat.m[13] = 0;
  66591. rmat.m[14] = 0;
  66592. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  66593. this._rotateWithMatrix(rmat, space, mesh);
  66594. };
  66595. /**
  66596. * Set the rotation of the bone to a particular axis angle in local or world space.
  66597. * @param axis The axis to rotate the bone on.
  66598. * @param angle The angle that the bone should be rotated to.
  66599. * @param space The space that the axis is in.
  66600. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66601. */
  66602. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  66603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66604. var rotMat = Bone._tmpMats[0];
  66605. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  66606. var rotMatInv = Bone._tmpMats[1];
  66607. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66608. rotMatInv.multiplyToRef(rotMat, rotMat);
  66609. this._rotateWithMatrix(rotMat, space, mesh);
  66610. };
  66611. /**
  66612. * Set the euler rotation of the bone in local of world space.
  66613. * @param rotation The euler rotation that the bone should be set to.
  66614. * @param space The space that the rotation is in.
  66615. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66616. */
  66617. Bone.prototype.setRotation = function (rotation, space, mesh) {
  66618. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66619. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  66620. };
  66621. /**
  66622. * Set the quaternion rotation of the bone in local of world space.
  66623. * @param quat The quaternion rotation that the bone should be set to.
  66624. * @param space The space that the rotation is in.
  66625. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66626. */
  66627. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  66628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66629. var rotMatInv = Bone._tmpMats[0];
  66630. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66631. var rotMat = Bone._tmpMats[1];
  66632. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  66633. rotMatInv.multiplyToRef(rotMat, rotMat);
  66634. this._rotateWithMatrix(rotMat, space, mesh);
  66635. };
  66636. /**
  66637. * Set the rotation matrix of the bone in local of world space.
  66638. * @param rotMat The rotation matrix that the bone should be set to.
  66639. * @param space The space that the rotation is in.
  66640. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66641. */
  66642. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  66643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66644. var rotMatInv = Bone._tmpMats[0];
  66645. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66646. var rotMat2 = Bone._tmpMats[1];
  66647. rotMat2.copyFrom(rotMat);
  66648. rotMatInv.multiplyToRef(rotMat, rotMat2);
  66649. this._rotateWithMatrix(rotMat2, space, mesh);
  66650. };
  66651. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  66652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66653. var lmat = this.getLocalMatrix();
  66654. var lx = lmat.m[12];
  66655. var ly = lmat.m[13];
  66656. var lz = lmat.m[14];
  66657. var parent = this.getParent();
  66658. var parentScale = Bone._tmpMats[3];
  66659. var parentScaleInv = Bone._tmpMats[4];
  66660. if (parent) {
  66661. if (space == BABYLON.Space.WORLD) {
  66662. if (mesh) {
  66663. parentScale.copyFrom(mesh.getWorldMatrix());
  66664. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  66665. }
  66666. else {
  66667. parentScale.copyFrom(parent.getAbsoluteTransform());
  66668. }
  66669. }
  66670. else {
  66671. parentScale = parent._scaleMatrix;
  66672. }
  66673. parentScaleInv.copyFrom(parentScale);
  66674. parentScaleInv.invert();
  66675. lmat.multiplyToRef(parentScale, lmat);
  66676. lmat.multiplyToRef(rmat, lmat);
  66677. lmat.multiplyToRef(parentScaleInv, lmat);
  66678. }
  66679. else {
  66680. if (space == BABYLON.Space.WORLD && mesh) {
  66681. parentScale.copyFrom(mesh.getWorldMatrix());
  66682. parentScaleInv.copyFrom(parentScale);
  66683. parentScaleInv.invert();
  66684. lmat.multiplyToRef(parentScale, lmat);
  66685. lmat.multiplyToRef(rmat, lmat);
  66686. lmat.multiplyToRef(parentScaleInv, lmat);
  66687. }
  66688. else {
  66689. lmat.multiplyToRef(rmat, lmat);
  66690. }
  66691. }
  66692. lmat.m[12] = lx;
  66693. lmat.m[13] = ly;
  66694. lmat.m[14] = lz;
  66695. this.computeAbsoluteTransforms();
  66696. this.markAsDirty();
  66697. };
  66698. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  66699. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66700. if (space == BABYLON.Space.WORLD) {
  66701. var scaleMatrix = Bone._tmpMats[2];
  66702. scaleMatrix.copyFrom(this._scaleMatrix);
  66703. rotMatInv.copyFrom(this.getAbsoluteTransform());
  66704. if (mesh) {
  66705. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  66706. var meshScale = Bone._tmpMats[3];
  66707. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  66708. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  66709. }
  66710. rotMatInv.invert();
  66711. scaleMatrix.m[0] *= this._scalingDeterminant;
  66712. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66713. }
  66714. else {
  66715. rotMatInv.copyFrom(this.getLocalMatrix());
  66716. rotMatInv.invert();
  66717. var scaleMatrix = Bone._tmpMats[2];
  66718. scaleMatrix.copyFrom(this._scaleMatrix);
  66719. if (this._parent) {
  66720. var pscaleMatrix = Bone._tmpMats[3];
  66721. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  66722. pscaleMatrix.invert();
  66723. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  66724. }
  66725. else {
  66726. scaleMatrix.m[0] *= this._scalingDeterminant;
  66727. }
  66728. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66729. }
  66730. };
  66731. /**
  66732. * Get the scale of the bone
  66733. * @returns the scale of the bone
  66734. */
  66735. Bone.prototype.getScale = function () {
  66736. return this._scaleVector.clone();
  66737. };
  66738. /**
  66739. * Copy the scale of the bone to a vector3.
  66740. * @param result The vector3 to copy the scale to
  66741. */
  66742. Bone.prototype.getScaleToRef = function (result) {
  66743. result.copyFrom(this._scaleVector);
  66744. };
  66745. /**
  66746. * Get the position of the bone in local or world space.
  66747. * @param space The space that the returned position is in.
  66748. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66749. * @returns The position of the bone
  66750. */
  66751. Bone.prototype.getPosition = function (space, mesh) {
  66752. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66753. if (mesh === void 0) { mesh = null; }
  66754. var pos = BABYLON.Vector3.Zero();
  66755. this.getPositionToRef(space, mesh, pos);
  66756. return pos;
  66757. };
  66758. /**
  66759. * Copy the position of the bone to a vector3 in local or world space.
  66760. * @param space The space that the returned position is in.
  66761. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66762. * @param result The vector3 to copy the position to.
  66763. */
  66764. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  66765. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66766. if (space == BABYLON.Space.LOCAL) {
  66767. var lm = this.getLocalMatrix();
  66768. result.x = lm.m[12];
  66769. result.y = lm.m[13];
  66770. result.z = lm.m[14];
  66771. }
  66772. else {
  66773. var wm = null;
  66774. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66775. if (mesh) {
  66776. wm = mesh.getWorldMatrix();
  66777. }
  66778. this._skeleton.computeAbsoluteTransforms();
  66779. var tmat = Bone._tmpMats[0];
  66780. if (mesh && wm) {
  66781. tmat.copyFrom(this.getAbsoluteTransform());
  66782. tmat.multiplyToRef(wm, tmat);
  66783. }
  66784. else {
  66785. tmat = this.getAbsoluteTransform();
  66786. }
  66787. result.x = tmat.m[12];
  66788. result.y = tmat.m[13];
  66789. result.z = tmat.m[14];
  66790. }
  66791. };
  66792. /**
  66793. * Get the absolute position of the bone (world space).
  66794. * @param mesh The mesh that this bone is attached to.
  66795. * @returns The absolute position of the bone
  66796. */
  66797. Bone.prototype.getAbsolutePosition = function (mesh) {
  66798. if (mesh === void 0) { mesh = null; }
  66799. var pos = BABYLON.Vector3.Zero();
  66800. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  66801. return pos;
  66802. };
  66803. /**
  66804. * Copy the absolute position of the bone (world space) to the result param.
  66805. * @param mesh The mesh that this bone is attached to.
  66806. * @param result The vector3 to copy the absolute position to.
  66807. */
  66808. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  66809. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  66810. };
  66811. /**
  66812. * Compute the absolute transforms of this bone and its children.
  66813. */
  66814. Bone.prototype.computeAbsoluteTransforms = function () {
  66815. if (this._parent) {
  66816. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66817. }
  66818. else {
  66819. this._absoluteTransform.copyFrom(this._localMatrix);
  66820. var poseMatrix = this._skeleton.getPoseMatrix();
  66821. if (poseMatrix) {
  66822. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  66823. }
  66824. }
  66825. var children = this.children;
  66826. var len = children.length;
  66827. for (var i = 0; i < len; i++) {
  66828. children[i].computeAbsoluteTransforms();
  66829. }
  66830. };
  66831. Bone.prototype._syncScaleVector = function () {
  66832. var lm = this.getLocalMatrix();
  66833. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  66834. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  66835. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  66836. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  66837. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  66838. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  66839. this._scaleVector.x = xs * Math.sqrt(xsq);
  66840. this._scaleVector.y = ys * Math.sqrt(ysq);
  66841. this._scaleVector.z = zs * Math.sqrt(zsq);
  66842. if (this._parent) {
  66843. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  66844. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  66845. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  66846. }
  66847. 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);
  66848. };
  66849. /**
  66850. * Get the world direction from an axis that is in the local space of the bone.
  66851. * @param localAxis The local direction that is used to compute the world direction.
  66852. * @param mesh The mesh that this bone is attached to.
  66853. * @returns The world direction
  66854. */
  66855. Bone.prototype.getDirection = function (localAxis, mesh) {
  66856. if (mesh === void 0) { mesh = null; }
  66857. var result = BABYLON.Vector3.Zero();
  66858. this.getDirectionToRef(localAxis, mesh, result);
  66859. return result;
  66860. };
  66861. /**
  66862. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  66863. * @param localAxis The local direction that is used to compute the world direction.
  66864. * @param mesh The mesh that this bone is attached to.
  66865. * @param result The vector3 that the world direction will be copied to.
  66866. */
  66867. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  66868. if (mesh === void 0) { mesh = null; }
  66869. var wm = null;
  66870. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66871. if (mesh) {
  66872. wm = mesh.getWorldMatrix();
  66873. }
  66874. this._skeleton.computeAbsoluteTransforms();
  66875. var mat = Bone._tmpMats[0];
  66876. mat.copyFrom(this.getAbsoluteTransform());
  66877. if (mesh && wm) {
  66878. mat.multiplyToRef(wm, mat);
  66879. }
  66880. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  66881. result.normalize();
  66882. };
  66883. /**
  66884. * Get the euler rotation of the bone in local or world space.
  66885. * @param space The space that the rotation should be in.
  66886. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66887. * @returns The euler rotation
  66888. */
  66889. Bone.prototype.getRotation = function (space, mesh) {
  66890. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66891. if (mesh === void 0) { mesh = null; }
  66892. var result = BABYLON.Vector3.Zero();
  66893. this.getRotationToRef(space, mesh, result);
  66894. return result;
  66895. };
  66896. /**
  66897. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  66898. * @param space The space that the rotation should be in.
  66899. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66900. * @param result The vector3 that the rotation should be copied to.
  66901. */
  66902. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  66903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66904. if (mesh === void 0) { mesh = null; }
  66905. var quat = Bone._tmpQuat;
  66906. this.getRotationQuaternionToRef(space, mesh, quat);
  66907. quat.toEulerAnglesToRef(result);
  66908. };
  66909. /**
  66910. * Get the quaternion rotation of the bone in either local or world space.
  66911. * @param space The space that the rotation should be in.
  66912. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66913. * @returns The quaternion rotation
  66914. */
  66915. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  66916. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66917. if (mesh === void 0) { mesh = null; }
  66918. var result = BABYLON.Quaternion.Identity();
  66919. this.getRotationQuaternionToRef(space, mesh, result);
  66920. return result;
  66921. };
  66922. /**
  66923. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  66924. * @param space The space that the rotation should be in.
  66925. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66926. * @param result The quaternion that the rotation should be copied to.
  66927. */
  66928. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  66929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66930. if (mesh === void 0) { mesh = null; }
  66931. if (space == BABYLON.Space.LOCAL) {
  66932. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66933. }
  66934. else {
  66935. var mat = Bone._tmpMats[0];
  66936. var amat = this.getAbsoluteTransform();
  66937. if (mesh) {
  66938. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66939. }
  66940. else {
  66941. mat.copyFrom(amat);
  66942. }
  66943. mat.m[0] *= this._scalingDeterminant;
  66944. mat.m[1] *= this._scalingDeterminant;
  66945. mat.m[2] *= this._scalingDeterminant;
  66946. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66947. }
  66948. };
  66949. /**
  66950. * Get the rotation matrix of the bone in local or world space.
  66951. * @param space The space that the rotation should be in.
  66952. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66953. * @returns The rotation matrix
  66954. */
  66955. Bone.prototype.getRotationMatrix = function (space, mesh) {
  66956. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66957. var result = BABYLON.Matrix.Identity();
  66958. this.getRotationMatrixToRef(space, mesh, result);
  66959. return result;
  66960. };
  66961. /**
  66962. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  66963. * @param space The space that the rotation should be in.
  66964. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66965. * @param result The quaternion that the rotation should be copied to.
  66966. */
  66967. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  66968. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66969. if (space == BABYLON.Space.LOCAL) {
  66970. this.getLocalMatrix().getRotationMatrixToRef(result);
  66971. }
  66972. else {
  66973. var mat = Bone._tmpMats[0];
  66974. var amat = this.getAbsoluteTransform();
  66975. if (mesh) {
  66976. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66977. }
  66978. else {
  66979. mat.copyFrom(amat);
  66980. }
  66981. mat.m[0] *= this._scalingDeterminant;
  66982. mat.m[1] *= this._scalingDeterminant;
  66983. mat.m[2] *= this._scalingDeterminant;
  66984. mat.getRotationMatrixToRef(result);
  66985. }
  66986. };
  66987. /**
  66988. * Get the world position of a point that is in the local space of the bone.
  66989. * @param position The local position
  66990. * @param mesh The mesh that this bone is attached to.
  66991. * @returns The world position
  66992. */
  66993. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  66994. if (mesh === void 0) { mesh = null; }
  66995. var result = BABYLON.Vector3.Zero();
  66996. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  66997. return result;
  66998. };
  66999. /**
  67000. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  67001. * @param position The local position
  67002. * @param mesh The mesh that this bone is attached to.
  67003. * @param result The vector3 that the world position should be copied to.
  67004. */
  67005. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  67006. if (mesh === void 0) { mesh = null; }
  67007. var wm = null;
  67008. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67009. if (mesh) {
  67010. wm = mesh.getWorldMatrix();
  67011. }
  67012. this._skeleton.computeAbsoluteTransforms();
  67013. var tmat = Bone._tmpMats[0];
  67014. if (mesh && wm) {
  67015. tmat.copyFrom(this.getAbsoluteTransform());
  67016. tmat.multiplyToRef(wm, tmat);
  67017. }
  67018. else {
  67019. tmat = this.getAbsoluteTransform();
  67020. }
  67021. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67022. };
  67023. /**
  67024. * Get the local position of a point that is in world space.
  67025. * @param position The world position
  67026. * @param mesh The mesh that this bone is attached to.
  67027. * @returns The local position
  67028. */
  67029. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  67030. if (mesh === void 0) { mesh = null; }
  67031. var result = BABYLON.Vector3.Zero();
  67032. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  67033. return result;
  67034. };
  67035. /**
  67036. * Get the local position of a point that is in world space and copy it to the result param.
  67037. * @param position The world position
  67038. * @param mesh The mesh that this bone is attached to.
  67039. * @param result The vector3 that the local position should be copied to.
  67040. */
  67041. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  67042. if (mesh === void 0) { mesh = null; }
  67043. var wm = null;
  67044. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67045. if (mesh) {
  67046. wm = mesh.getWorldMatrix();
  67047. }
  67048. this._skeleton.computeAbsoluteTransforms();
  67049. var tmat = Bone._tmpMats[0];
  67050. tmat.copyFrom(this.getAbsoluteTransform());
  67051. if (mesh && wm) {
  67052. tmat.multiplyToRef(wm, tmat);
  67053. }
  67054. tmat.invert();
  67055. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67056. };
  67057. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67058. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  67059. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67060. return Bone;
  67061. }(BABYLON.Node));
  67062. BABYLON.Bone = Bone;
  67063. })(BABYLON || (BABYLON = {}));
  67064. //# sourceMappingURL=babylon.bone.js.map
  67065. var BABYLON;
  67066. (function (BABYLON) {
  67067. var BoneIKController = /** @class */ (function () {
  67068. function BoneIKController(mesh, bone, options) {
  67069. this.targetPosition = BABYLON.Vector3.Zero();
  67070. this.poleTargetPosition = BABYLON.Vector3.Zero();
  67071. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  67072. this.poleAngle = 0;
  67073. this.slerpAmount = 1;
  67074. this._bone1Quat = BABYLON.Quaternion.Identity();
  67075. this._bone1Mat = BABYLON.Matrix.Identity();
  67076. this._bone2Ang = Math.PI;
  67077. this._maxAngle = Math.PI;
  67078. this._rightHandedSystem = false;
  67079. this._bendAxis = BABYLON.Vector3.Right();
  67080. this._slerping = false;
  67081. this._adjustRoll = 0;
  67082. this._bone2 = bone;
  67083. this._bone1 = bone.getParent();
  67084. if (!this._bone1) {
  67085. return;
  67086. }
  67087. this.mesh = mesh;
  67088. var bonePos = bone.getPosition();
  67089. if (bone.getAbsoluteTransform().determinant() > 0) {
  67090. this._rightHandedSystem = true;
  67091. this._bendAxis.x = 0;
  67092. this._bendAxis.y = 0;
  67093. this._bendAxis.z = -1;
  67094. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  67095. this._adjustRoll = Math.PI * .5;
  67096. this._bendAxis.z = 1;
  67097. }
  67098. }
  67099. if (this._bone1.length) {
  67100. var boneScale1 = this._bone1.getScale();
  67101. var boneScale2 = this._bone2.getScale();
  67102. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  67103. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  67104. }
  67105. else if (this._bone1.children[0]) {
  67106. mesh.computeWorldMatrix(true);
  67107. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  67108. var pos2 = this._bone2.getAbsolutePosition(mesh);
  67109. var pos3 = this._bone1.getAbsolutePosition(mesh);
  67110. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  67111. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  67112. }
  67113. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  67114. this.maxAngle = Math.PI;
  67115. if (options) {
  67116. if (options.targetMesh) {
  67117. this.targetMesh = options.targetMesh;
  67118. this.targetMesh.computeWorldMatrix(true);
  67119. }
  67120. if (options.poleTargetMesh) {
  67121. this.poleTargetMesh = options.poleTargetMesh;
  67122. this.poleTargetMesh.computeWorldMatrix(true);
  67123. }
  67124. else if (options.poleTargetBone) {
  67125. this.poleTargetBone = options.poleTargetBone;
  67126. }
  67127. else if (this._bone1.getParent()) {
  67128. this.poleTargetBone = this._bone1.getParent();
  67129. }
  67130. if (options.poleTargetLocalOffset) {
  67131. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  67132. }
  67133. if (options.poleAngle) {
  67134. this.poleAngle = options.poleAngle;
  67135. }
  67136. if (options.bendAxis) {
  67137. this._bendAxis.copyFrom(options.bendAxis);
  67138. }
  67139. if (options.maxAngle) {
  67140. this.maxAngle = options.maxAngle;
  67141. }
  67142. if (options.slerpAmount) {
  67143. this.slerpAmount = options.slerpAmount;
  67144. }
  67145. }
  67146. }
  67147. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  67148. get: function () {
  67149. return this._maxAngle;
  67150. },
  67151. set: function (value) {
  67152. this._setMaxAngle(value);
  67153. },
  67154. enumerable: true,
  67155. configurable: true
  67156. });
  67157. BoneIKController.prototype._setMaxAngle = function (ang) {
  67158. if (ang < 0) {
  67159. ang = 0;
  67160. }
  67161. if (ang > Math.PI || ang == undefined) {
  67162. ang = Math.PI;
  67163. }
  67164. this._maxAngle = ang;
  67165. var a = this._bone1Length;
  67166. var b = this._bone2Length;
  67167. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  67168. };
  67169. BoneIKController.prototype.update = function () {
  67170. var bone1 = this._bone1;
  67171. if (!bone1) {
  67172. return;
  67173. }
  67174. var target = this.targetPosition;
  67175. var poleTarget = this.poleTargetPosition;
  67176. var mat1 = BoneIKController._tmpMats[0];
  67177. var mat2 = BoneIKController._tmpMats[1];
  67178. if (this.targetMesh) {
  67179. target.copyFrom(this.targetMesh.getAbsolutePosition());
  67180. }
  67181. if (this.poleTargetBone) {
  67182. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  67183. }
  67184. else if (this.poleTargetMesh) {
  67185. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  67186. }
  67187. var bonePos = BoneIKController._tmpVecs[0];
  67188. var zaxis = BoneIKController._tmpVecs[1];
  67189. var xaxis = BoneIKController._tmpVecs[2];
  67190. var yaxis = BoneIKController._tmpVecs[3];
  67191. var upAxis = BoneIKController._tmpVecs[4];
  67192. var _tmpQuat = BoneIKController._tmpQuat;
  67193. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  67194. poleTarget.subtractToRef(bonePos, upAxis);
  67195. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  67196. upAxis.y = 1;
  67197. }
  67198. else {
  67199. upAxis.normalize();
  67200. }
  67201. target.subtractToRef(bonePos, yaxis);
  67202. yaxis.normalize();
  67203. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  67204. zaxis.normalize();
  67205. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  67206. xaxis.normalize();
  67207. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  67208. var a = this._bone1Length;
  67209. var b = this._bone2Length;
  67210. var c = BABYLON.Vector3.Distance(bonePos, target);
  67211. if (this._maxReach > 0) {
  67212. c = Math.min(this._maxReach, c);
  67213. }
  67214. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  67215. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  67216. if (acosa > 1) {
  67217. acosa = 1;
  67218. }
  67219. if (acosb > 1) {
  67220. acosb = 1;
  67221. }
  67222. if (acosa < -1) {
  67223. acosa = -1;
  67224. }
  67225. if (acosb < -1) {
  67226. acosb = -1;
  67227. }
  67228. var angA = Math.acos(acosa);
  67229. var angB = Math.acos(acosb);
  67230. var angC = -angA - angB;
  67231. if (this._rightHandedSystem) {
  67232. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  67233. mat2.multiplyToRef(mat1, mat1);
  67234. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  67235. mat2.multiplyToRef(mat1, mat1);
  67236. }
  67237. else {
  67238. var _tmpVec = BoneIKController._tmpVecs[5];
  67239. _tmpVec.copyFrom(this._bendAxis);
  67240. _tmpVec.x *= -1;
  67241. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  67242. mat2.multiplyToRef(mat1, mat1);
  67243. }
  67244. if (this.poleAngle) {
  67245. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  67246. mat1.multiplyToRef(mat2, mat1);
  67247. }
  67248. if (this._bone1) {
  67249. if (this.slerpAmount < 1) {
  67250. if (!this._slerping) {
  67251. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  67252. }
  67253. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  67254. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  67255. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  67256. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  67257. this._slerping = true;
  67258. }
  67259. else {
  67260. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  67261. this._bone1Mat.copyFrom(mat1);
  67262. this._slerping = false;
  67263. }
  67264. }
  67265. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  67266. this._bone2Ang = angC;
  67267. };
  67268. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67269. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  67270. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67271. return BoneIKController;
  67272. }());
  67273. BABYLON.BoneIKController = BoneIKController;
  67274. })(BABYLON || (BABYLON = {}));
  67275. //# sourceMappingURL=babylon.boneIKController.js.map
  67276. var BABYLON;
  67277. (function (BABYLON) {
  67278. var BoneLookController = /** @class */ (function () {
  67279. /**
  67280. * Create a BoneLookController
  67281. * @param mesh the mesh that the bone belongs to
  67282. * @param bone the bone that will be looking to the target
  67283. * @param target the target Vector3 to look at
  67284. * @param settings optional settings:
  67285. * - maxYaw: the maximum angle the bone will yaw to
  67286. * - minYaw: the minimum angle the bone will yaw to
  67287. * - maxPitch: the maximum angle the bone will pitch to
  67288. * - minPitch: the minimum angle the bone will yaw to
  67289. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  67290. * - upAxis: the up axis of the coordinate system
  67291. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67292. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  67293. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  67294. * - adjustYaw: used to make an adjustment to the yaw of the bone
  67295. * - adjustPitch: used to make an adjustment to the pitch of the bone
  67296. * - adjustRoll: used to make an adjustment to the roll of the bone
  67297. **/
  67298. function BoneLookController(mesh, bone, target, options) {
  67299. /**
  67300. * The up axis of the coordinate system that is used when the bone is rotated.
  67301. */
  67302. this.upAxis = BABYLON.Vector3.Up();
  67303. /**
  67304. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67305. */
  67306. this.upAxisSpace = BABYLON.Space.LOCAL;
  67307. /**
  67308. * Used to make an adjustment to the yaw of the bone.
  67309. */
  67310. this.adjustYaw = 0;
  67311. /**
  67312. * Used to make an adjustment to the pitch of the bone.
  67313. */
  67314. this.adjustPitch = 0;
  67315. /**
  67316. * Used to make an adjustment to the roll of the bone.
  67317. */
  67318. this.adjustRoll = 0;
  67319. /**
  67320. * 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).
  67321. */
  67322. this.slerpAmount = 1;
  67323. this._boneQuat = BABYLON.Quaternion.Identity();
  67324. this._slerping = false;
  67325. this._firstFrameSkipped = false;
  67326. this._fowardAxis = BABYLON.Vector3.Forward();
  67327. this.mesh = mesh;
  67328. this.bone = bone;
  67329. this.target = target;
  67330. if (options) {
  67331. if (options.adjustYaw) {
  67332. this.adjustYaw = options.adjustYaw;
  67333. }
  67334. if (options.adjustPitch) {
  67335. this.adjustPitch = options.adjustPitch;
  67336. }
  67337. if (options.adjustRoll) {
  67338. this.adjustRoll = options.adjustRoll;
  67339. }
  67340. if (options.maxYaw != null) {
  67341. this.maxYaw = options.maxYaw;
  67342. }
  67343. else {
  67344. this.maxYaw = Math.PI;
  67345. }
  67346. if (options.minYaw != null) {
  67347. this.minYaw = options.minYaw;
  67348. }
  67349. else {
  67350. this.minYaw = -Math.PI;
  67351. }
  67352. if (options.maxPitch != null) {
  67353. this.maxPitch = options.maxPitch;
  67354. }
  67355. else {
  67356. this.maxPitch = Math.PI;
  67357. }
  67358. if (options.minPitch != null) {
  67359. this.minPitch = options.minPitch;
  67360. }
  67361. else {
  67362. this.minPitch = -Math.PI;
  67363. }
  67364. if (options.slerpAmount != null) {
  67365. this.slerpAmount = options.slerpAmount;
  67366. }
  67367. if (options.upAxis != null) {
  67368. this.upAxis = options.upAxis;
  67369. }
  67370. if (options.upAxisSpace != null) {
  67371. this.upAxisSpace = options.upAxisSpace;
  67372. }
  67373. if (options.yawAxis != null || options.pitchAxis != null) {
  67374. var newYawAxis = BABYLON.Axis.Y;
  67375. var newPitchAxis = BABYLON.Axis.X;
  67376. if (options.yawAxis != null) {
  67377. newYawAxis = options.yawAxis.clone();
  67378. newYawAxis.normalize();
  67379. }
  67380. if (options.pitchAxis != null) {
  67381. newPitchAxis = options.pitchAxis.clone();
  67382. newPitchAxis.normalize();
  67383. }
  67384. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  67385. this._transformYawPitch = BABYLON.Matrix.Identity();
  67386. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  67387. this._transformYawPitchInv = this._transformYawPitch.clone();
  67388. this._transformYawPitch.invert();
  67389. }
  67390. }
  67391. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  67392. this.upAxisSpace = BABYLON.Space.LOCAL;
  67393. }
  67394. }
  67395. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  67396. /**
  67397. * Get/set the minimum yaw angle that the bone can look to.
  67398. */
  67399. get: function () {
  67400. return this._minYaw;
  67401. },
  67402. set: function (value) {
  67403. this._minYaw = value;
  67404. this._minYawSin = Math.sin(value);
  67405. this._minYawCos = Math.cos(value);
  67406. if (this._maxYaw != null) {
  67407. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67408. this._yawRange = this._maxYaw - this._minYaw;
  67409. }
  67410. },
  67411. enumerable: true,
  67412. configurable: true
  67413. });
  67414. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  67415. /**
  67416. * Get/set the maximum yaw angle that the bone can look to.
  67417. */
  67418. get: function () {
  67419. return this._maxYaw;
  67420. },
  67421. set: function (value) {
  67422. this._maxYaw = value;
  67423. this._maxYawSin = Math.sin(value);
  67424. this._maxYawCos = Math.cos(value);
  67425. if (this._minYaw != null) {
  67426. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67427. this._yawRange = this._maxYaw - this._minYaw;
  67428. }
  67429. },
  67430. enumerable: true,
  67431. configurable: true
  67432. });
  67433. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  67434. /**
  67435. * Get/set the minimum pitch angle that the bone can look to.
  67436. */
  67437. get: function () {
  67438. return this._minPitch;
  67439. },
  67440. set: function (value) {
  67441. this._minPitch = value;
  67442. this._minPitchTan = Math.tan(value);
  67443. },
  67444. enumerable: true,
  67445. configurable: true
  67446. });
  67447. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  67448. /**
  67449. * Get/set the maximum pitch angle that the bone can look to.
  67450. */
  67451. get: function () {
  67452. return this._maxPitch;
  67453. },
  67454. set: function (value) {
  67455. this._maxPitch = value;
  67456. this._maxPitchTan = Math.tan(value);
  67457. },
  67458. enumerable: true,
  67459. configurable: true
  67460. });
  67461. /**
  67462. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  67463. */
  67464. BoneLookController.prototype.update = function () {
  67465. //skip the first frame when slerping so that the mesh rotation is correct
  67466. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  67467. this._firstFrameSkipped = true;
  67468. return;
  67469. }
  67470. var bone = this.bone;
  67471. var bonePos = BoneLookController._tmpVecs[0];
  67472. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  67473. var target = this.target;
  67474. var _tmpMat1 = BoneLookController._tmpMats[0];
  67475. var _tmpMat2 = BoneLookController._tmpMats[1];
  67476. var mesh = this.mesh;
  67477. var parentBone = bone.getParent();
  67478. var upAxis = BoneLookController._tmpVecs[1];
  67479. upAxis.copyFrom(this.upAxis);
  67480. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  67481. if (this._transformYawPitch) {
  67482. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  67483. }
  67484. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  67485. }
  67486. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  67487. mesh.getDirectionToRef(upAxis, upAxis);
  67488. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  67489. upAxis.normalize();
  67490. }
  67491. }
  67492. var checkYaw = false;
  67493. var checkPitch = false;
  67494. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  67495. checkYaw = true;
  67496. }
  67497. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  67498. checkPitch = true;
  67499. }
  67500. if (checkYaw || checkPitch) {
  67501. var spaceMat = BoneLookController._tmpMats[2];
  67502. var spaceMatInv = BoneLookController._tmpMats[3];
  67503. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  67504. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  67505. }
  67506. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  67507. spaceMat.copyFrom(mesh.getWorldMatrix());
  67508. }
  67509. else {
  67510. var forwardAxis = BoneLookController._tmpVecs[2];
  67511. forwardAxis.copyFrom(this._fowardAxis);
  67512. if (this._transformYawPitch) {
  67513. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  67514. }
  67515. if (parentBone) {
  67516. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  67517. }
  67518. else {
  67519. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  67520. }
  67521. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  67522. rightAxis.normalize();
  67523. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  67524. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  67525. }
  67526. spaceMat.invertToRef(spaceMatInv);
  67527. var xzlen = null;
  67528. if (checkPitch) {
  67529. var localTarget = BoneLookController._tmpVecs[3];
  67530. target.subtractToRef(bonePos, localTarget);
  67531. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67532. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67533. var pitch = Math.atan2(localTarget.y, xzlen);
  67534. var newPitch = pitch;
  67535. if (pitch > this._maxPitch) {
  67536. localTarget.y = this._maxPitchTan * xzlen;
  67537. newPitch = this._maxPitch;
  67538. }
  67539. else if (pitch < this._minPitch) {
  67540. localTarget.y = this._minPitchTan * xzlen;
  67541. newPitch = this._minPitch;
  67542. }
  67543. if (pitch != newPitch) {
  67544. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67545. localTarget.addInPlace(bonePos);
  67546. target = localTarget;
  67547. }
  67548. }
  67549. if (checkYaw) {
  67550. var localTarget = BoneLookController._tmpVecs[4];
  67551. target.subtractToRef(bonePos, localTarget);
  67552. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67553. var yaw = Math.atan2(localTarget.x, localTarget.z);
  67554. var newYaw = yaw;
  67555. if (yaw > this._maxYaw || yaw < this._minYaw) {
  67556. if (xzlen == null) {
  67557. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67558. }
  67559. if (this._yawRange > Math.PI) {
  67560. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  67561. localTarget.z = this._maxYawCos * xzlen;
  67562. localTarget.x = this._maxYawSin * xzlen;
  67563. newYaw = this._maxYaw;
  67564. }
  67565. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  67566. localTarget.z = this._minYawCos * xzlen;
  67567. localTarget.x = this._minYawSin * xzlen;
  67568. newYaw = this._minYaw;
  67569. }
  67570. }
  67571. else {
  67572. if (yaw > this._maxYaw) {
  67573. localTarget.z = this._maxYawCos * xzlen;
  67574. localTarget.x = this._maxYawSin * xzlen;
  67575. newYaw = this._maxYaw;
  67576. }
  67577. else if (yaw < this._minYaw) {
  67578. localTarget.z = this._minYawCos * xzlen;
  67579. localTarget.x = this._minYawSin * xzlen;
  67580. newYaw = this._minYaw;
  67581. }
  67582. }
  67583. }
  67584. if (this._slerping && this._yawRange > Math.PI) {
  67585. //are we going to be crossing into the min/max region?
  67586. var boneFwd = BoneLookController._tmpVecs[8];
  67587. boneFwd.copyFrom(BABYLON.Axis.Z);
  67588. if (this._transformYawPitch) {
  67589. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  67590. }
  67591. var boneRotMat = BoneLookController._tmpMats[4];
  67592. this._boneQuat.toRotationMatrix(boneRotMat);
  67593. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  67594. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  67595. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  67596. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  67597. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  67598. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  67599. if (angBtwTar > angBtwMidYaw) {
  67600. if (xzlen == null) {
  67601. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67602. }
  67603. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  67604. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  67605. if (angBtwMin < angBtwMax) {
  67606. newYaw = boneYaw + Math.PI * .75;
  67607. localTarget.z = Math.cos(newYaw) * xzlen;
  67608. localTarget.x = Math.sin(newYaw) * xzlen;
  67609. }
  67610. else {
  67611. newYaw = boneYaw - Math.PI * .75;
  67612. localTarget.z = Math.cos(newYaw) * xzlen;
  67613. localTarget.x = Math.sin(newYaw) * xzlen;
  67614. }
  67615. }
  67616. }
  67617. if (yaw != newYaw) {
  67618. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67619. localTarget.addInPlace(bonePos);
  67620. target = localTarget;
  67621. }
  67622. }
  67623. }
  67624. var zaxis = BoneLookController._tmpVecs[5];
  67625. var xaxis = BoneLookController._tmpVecs[6];
  67626. var yaxis = BoneLookController._tmpVecs[7];
  67627. var _tmpQuat = BoneLookController._tmpQuat;
  67628. target.subtractToRef(bonePos, zaxis);
  67629. zaxis.normalize();
  67630. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  67631. xaxis.normalize();
  67632. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  67633. yaxis.normalize();
  67634. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  67635. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  67636. return;
  67637. }
  67638. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  67639. return;
  67640. }
  67641. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  67642. return;
  67643. }
  67644. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  67645. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  67646. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  67647. }
  67648. if (this.slerpAmount < 1) {
  67649. if (!this._slerping) {
  67650. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  67651. }
  67652. if (this._transformYawPitch) {
  67653. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67654. }
  67655. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  67656. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  67657. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  67658. this._slerping = true;
  67659. }
  67660. else {
  67661. if (this._transformYawPitch) {
  67662. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67663. }
  67664. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  67665. this._slerping = false;
  67666. }
  67667. };
  67668. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  67669. var angDiff = ang2 - ang1;
  67670. angDiff %= Math.PI * 2;
  67671. if (angDiff > Math.PI) {
  67672. angDiff -= Math.PI * 2;
  67673. }
  67674. else if (angDiff < -Math.PI) {
  67675. angDiff += Math.PI * 2;
  67676. }
  67677. return angDiff;
  67678. };
  67679. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  67680. ang1 %= (2 * Math.PI);
  67681. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67682. ang2 %= (2 * Math.PI);
  67683. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67684. var ab = 0;
  67685. if (ang1 < ang2) {
  67686. ab = ang2 - ang1;
  67687. }
  67688. else {
  67689. ab = ang1 - ang2;
  67690. }
  67691. if (ab > Math.PI) {
  67692. ab = Math.PI * 2 - ab;
  67693. }
  67694. return ab;
  67695. };
  67696. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  67697. ang %= (2 * Math.PI);
  67698. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  67699. ang1 %= (2 * Math.PI);
  67700. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67701. ang2 %= (2 * Math.PI);
  67702. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67703. if (ang1 < ang2) {
  67704. if (ang > ang1 && ang < ang2) {
  67705. return true;
  67706. }
  67707. }
  67708. else {
  67709. if (ang > ang2 && ang < ang1) {
  67710. return true;
  67711. }
  67712. }
  67713. return false;
  67714. };
  67715. 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()];
  67716. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  67717. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67718. return BoneLookController;
  67719. }());
  67720. BABYLON.BoneLookController = BoneLookController;
  67721. })(BABYLON || (BABYLON = {}));
  67722. //# sourceMappingURL=babylon.boneLookController.js.map
  67723. var BABYLON;
  67724. (function (BABYLON) {
  67725. var Skeleton = /** @class */ (function () {
  67726. function Skeleton(name, id, scene) {
  67727. this.name = name;
  67728. this.id = id;
  67729. this.bones = new Array();
  67730. this.needInitialSkinMatrix = false;
  67731. this._isDirty = true;
  67732. this._meshesWithPoseMatrix = new Array();
  67733. this._identity = BABYLON.Matrix.Identity();
  67734. this._ranges = {};
  67735. this._lastAbsoluteTransformsUpdateId = -1;
  67736. // Events
  67737. /**
  67738. * An event triggered before computing the skeleton's matrices
  67739. * @type {BABYLON.Observable}
  67740. */
  67741. this.onBeforeComputeObservable = new BABYLON.Observable();
  67742. this.bones = [];
  67743. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67744. scene.skeletons.push(this);
  67745. //make sure it will recalculate the matrix next time prepare is called.
  67746. this._isDirty = true;
  67747. }
  67748. // Members
  67749. Skeleton.prototype.getTransformMatrices = function (mesh) {
  67750. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  67751. return mesh._bonesTransformMatrices;
  67752. }
  67753. if (!this._transformMatrices) {
  67754. this.prepare();
  67755. }
  67756. return this._transformMatrices;
  67757. };
  67758. Skeleton.prototype.getScene = function () {
  67759. return this._scene;
  67760. };
  67761. // Methods
  67762. /**
  67763. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  67764. */
  67765. Skeleton.prototype.toString = function (fullDetails) {
  67766. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  67767. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  67768. if (fullDetails) {
  67769. ret += ", Ranges: {";
  67770. var first = true;
  67771. for (var name_1 in this._ranges) {
  67772. if (first) {
  67773. ret += ", ";
  67774. first = false;
  67775. }
  67776. ret += name_1;
  67777. }
  67778. ret += "}";
  67779. }
  67780. return ret;
  67781. };
  67782. /**
  67783. * Get bone's index searching by name
  67784. * @param {string} name is bone's name to search for
  67785. * @return {number} Indice of the bone. Returns -1 if not found
  67786. */
  67787. Skeleton.prototype.getBoneIndexByName = function (name) {
  67788. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  67789. if (this.bones[boneIndex].name === name) {
  67790. return boneIndex;
  67791. }
  67792. }
  67793. return -1;
  67794. };
  67795. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  67796. // check name not already in use
  67797. if (!this._ranges[name]) {
  67798. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  67799. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67800. if (this.bones[i].animations[0]) {
  67801. this.bones[i].animations[0].createRange(name, from, to);
  67802. }
  67803. }
  67804. }
  67805. };
  67806. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  67807. if (deleteFrames === void 0) { deleteFrames = true; }
  67808. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67809. if (this.bones[i].animations[0]) {
  67810. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  67811. }
  67812. }
  67813. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  67814. };
  67815. Skeleton.prototype.getAnimationRange = function (name) {
  67816. return this._ranges[name];
  67817. };
  67818. /**
  67819. * Returns as an Array, all AnimationRanges defined on this skeleton
  67820. */
  67821. Skeleton.prototype.getAnimationRanges = function () {
  67822. var animationRanges = [];
  67823. var name;
  67824. var i = 0;
  67825. for (name in this._ranges) {
  67826. animationRanges[i] = this._ranges[name];
  67827. i++;
  67828. }
  67829. return animationRanges;
  67830. };
  67831. /**
  67832. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  67833. */
  67834. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  67835. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67836. if (this._ranges[name] || !source.getAnimationRange(name)) {
  67837. return false;
  67838. }
  67839. var ret = true;
  67840. var frameOffset = this._getHighestAnimationFrame() + 1;
  67841. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  67842. var boneDict = {};
  67843. var sourceBones = source.bones;
  67844. var nBones;
  67845. var i;
  67846. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  67847. boneDict[sourceBones[i].name] = sourceBones[i];
  67848. }
  67849. if (this.bones.length !== sourceBones.length) {
  67850. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  67851. ret = false;
  67852. }
  67853. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  67854. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  67855. var boneName = this.bones[i].name;
  67856. var sourceBone = boneDict[boneName];
  67857. if (sourceBone) {
  67858. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  67859. }
  67860. else {
  67861. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  67862. ret = false;
  67863. }
  67864. }
  67865. // do not call createAnimationRange(), since it also is done to bones, which was already done
  67866. var range = source.getAnimationRange(name);
  67867. if (range) {
  67868. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  67869. }
  67870. return ret;
  67871. };
  67872. Skeleton.prototype.returnToRest = function () {
  67873. for (var index = 0; index < this.bones.length; index++) {
  67874. this.bones[index].returnToRest();
  67875. }
  67876. };
  67877. Skeleton.prototype._getHighestAnimationFrame = function () {
  67878. var ret = 0;
  67879. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67880. if (this.bones[i].animations[0]) {
  67881. var highest = this.bones[i].animations[0].getHighestFrame();
  67882. if (ret < highest) {
  67883. ret = highest;
  67884. }
  67885. }
  67886. }
  67887. return ret;
  67888. };
  67889. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  67890. var range = this.getAnimationRange(name);
  67891. if (!range) {
  67892. return null;
  67893. }
  67894. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  67895. };
  67896. Skeleton.prototype._markAsDirty = function () {
  67897. this._isDirty = true;
  67898. };
  67899. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  67900. this._meshesWithPoseMatrix.push(mesh);
  67901. };
  67902. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  67903. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  67904. if (index > -1) {
  67905. this._meshesWithPoseMatrix.splice(index, 1);
  67906. }
  67907. };
  67908. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  67909. this.onBeforeComputeObservable.notifyObservers(this);
  67910. for (var index = 0; index < this.bones.length; index++) {
  67911. var bone = this.bones[index];
  67912. var parentBone = bone.getParent();
  67913. if (parentBone) {
  67914. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  67915. }
  67916. else {
  67917. if (initialSkinMatrix) {
  67918. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  67919. }
  67920. else {
  67921. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  67922. }
  67923. }
  67924. if (bone._index !== -1) {
  67925. var mappedIndex = bone._index === null ? index : bone._index;
  67926. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  67927. }
  67928. }
  67929. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  67930. };
  67931. Skeleton.prototype.prepare = function () {
  67932. if (!this._isDirty) {
  67933. return;
  67934. }
  67935. if (this.needInitialSkinMatrix) {
  67936. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  67937. var mesh = this._meshesWithPoseMatrix[index];
  67938. var poseMatrix = mesh.getPoseMatrix();
  67939. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  67940. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67941. }
  67942. if (this._synchronizedWithMesh !== mesh) {
  67943. this._synchronizedWithMesh = mesh;
  67944. // Prepare bones
  67945. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  67946. var bone = this.bones[boneIndex];
  67947. if (!bone.getParent()) {
  67948. var matrix = bone.getBaseMatrix();
  67949. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  67950. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  67951. }
  67952. }
  67953. }
  67954. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  67955. }
  67956. }
  67957. else {
  67958. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  67959. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67960. }
  67961. this._computeTransformMatrices(this._transformMatrices, null);
  67962. }
  67963. this._isDirty = false;
  67964. this._scene._activeBones.addCount(this.bones.length, false);
  67965. };
  67966. Skeleton.prototype.getAnimatables = function () {
  67967. if (!this._animatables || this._animatables.length !== this.bones.length) {
  67968. this._animatables = [];
  67969. for (var index = 0; index < this.bones.length; index++) {
  67970. this._animatables.push(this.bones[index]);
  67971. }
  67972. }
  67973. return this._animatables;
  67974. };
  67975. Skeleton.prototype.clone = function (name, id) {
  67976. var result = new Skeleton(name, id || name, this._scene);
  67977. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67978. for (var index = 0; index < this.bones.length; index++) {
  67979. var source = this.bones[index];
  67980. var parentBone = null;
  67981. var parent_1 = source.getParent();
  67982. if (parent_1) {
  67983. var parentIndex = this.bones.indexOf(parent_1);
  67984. parentBone = result.bones[parentIndex];
  67985. }
  67986. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  67987. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  67988. }
  67989. if (this._ranges) {
  67990. result._ranges = {};
  67991. for (var rangeName in this._ranges) {
  67992. var range = this._ranges[rangeName];
  67993. if (range) {
  67994. result._ranges[rangeName] = range.clone();
  67995. }
  67996. }
  67997. }
  67998. this._isDirty = true;
  67999. return result;
  68000. };
  68001. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  68002. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  68003. this.bones.forEach(function (bone) {
  68004. bone.animations.forEach(function (animation) {
  68005. animation.enableBlending = true;
  68006. animation.blendingSpeed = blendingSpeed;
  68007. });
  68008. });
  68009. };
  68010. Skeleton.prototype.dispose = function () {
  68011. this._meshesWithPoseMatrix = [];
  68012. // Animations
  68013. this.getScene().stopAnimation(this);
  68014. // Remove from scene
  68015. this.getScene().removeSkeleton(this);
  68016. };
  68017. Skeleton.prototype.serialize = function () {
  68018. var serializationObject = {};
  68019. serializationObject.name = this.name;
  68020. serializationObject.id = this.id;
  68021. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  68022. serializationObject.bones = [];
  68023. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68024. for (var index = 0; index < this.bones.length; index++) {
  68025. var bone = this.bones[index];
  68026. var parent_2 = bone.getParent();
  68027. var serializedBone = {
  68028. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  68029. name: bone.name,
  68030. matrix: bone.getBaseMatrix().toArray(),
  68031. rest: bone.getRestPose().toArray()
  68032. };
  68033. serializationObject.bones.push(serializedBone);
  68034. if (bone.length) {
  68035. serializedBone.length = bone.length;
  68036. }
  68037. if (bone.animations && bone.animations.length > 0) {
  68038. serializedBone.animation = bone.animations[0].serialize();
  68039. }
  68040. serializationObject.ranges = [];
  68041. for (var name in this._ranges) {
  68042. var source = this._ranges[name];
  68043. if (!source) {
  68044. continue;
  68045. }
  68046. var range = {};
  68047. range.name = name;
  68048. range.from = source.from;
  68049. range.to = source.to;
  68050. serializationObject.ranges.push(range);
  68051. }
  68052. }
  68053. return serializationObject;
  68054. };
  68055. Skeleton.Parse = function (parsedSkeleton, scene) {
  68056. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  68057. if (parsedSkeleton.dimensionsAtRest) {
  68058. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  68059. }
  68060. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  68061. var index;
  68062. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  68063. var parsedBone = parsedSkeleton.bones[index];
  68064. var parentBone = null;
  68065. if (parsedBone.parentBoneIndex > -1) {
  68066. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  68067. }
  68068. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  68069. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  68070. if (parsedBone.length) {
  68071. bone.length = parsedBone.length;
  68072. }
  68073. if (parsedBone.animation) {
  68074. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  68075. }
  68076. }
  68077. // placed after bones, so createAnimationRange can cascade down
  68078. if (parsedSkeleton.ranges) {
  68079. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  68080. var data = parsedSkeleton.ranges[index];
  68081. skeleton.createAnimationRange(data.name, data.from, data.to);
  68082. }
  68083. }
  68084. return skeleton;
  68085. };
  68086. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  68087. if (forceUpdate === void 0) { forceUpdate = false; }
  68088. var renderId = this._scene.getRenderId();
  68089. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  68090. this.bones[0].computeAbsoluteTransforms();
  68091. this._lastAbsoluteTransformsUpdateId = renderId;
  68092. }
  68093. };
  68094. Skeleton.prototype.getPoseMatrix = function () {
  68095. var poseMatrix = null;
  68096. if (this._meshesWithPoseMatrix.length > 0) {
  68097. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  68098. }
  68099. return poseMatrix;
  68100. };
  68101. Skeleton.prototype.sortBones = function () {
  68102. var bones = new Array();
  68103. var visited = new Array(this.bones.length);
  68104. for (var index = 0; index < this.bones.length; index++) {
  68105. this._sortBones(index, bones, visited);
  68106. }
  68107. this.bones = bones;
  68108. };
  68109. Skeleton.prototype._sortBones = function (index, bones, visited) {
  68110. if (visited[index]) {
  68111. return;
  68112. }
  68113. visited[index] = true;
  68114. var bone = this.bones[index];
  68115. if (bone._index === undefined) {
  68116. bone._index = index;
  68117. }
  68118. var parentBone = bone.getParent();
  68119. if (parentBone) {
  68120. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  68121. }
  68122. bones.push(bone);
  68123. };
  68124. return Skeleton;
  68125. }());
  68126. BABYLON.Skeleton = Skeleton;
  68127. })(BABYLON || (BABYLON = {}));
  68128. //# sourceMappingURL=babylon.skeleton.js.map
  68129. var BABYLON;
  68130. (function (BABYLON) {
  68131. var SphericalPolynomial = /** @class */ (function () {
  68132. function SphericalPolynomial() {
  68133. this.x = BABYLON.Vector3.Zero();
  68134. this.y = BABYLON.Vector3.Zero();
  68135. this.z = BABYLON.Vector3.Zero();
  68136. this.xx = BABYLON.Vector3.Zero();
  68137. this.yy = BABYLON.Vector3.Zero();
  68138. this.zz = BABYLON.Vector3.Zero();
  68139. this.xy = BABYLON.Vector3.Zero();
  68140. this.yz = BABYLON.Vector3.Zero();
  68141. this.zx = BABYLON.Vector3.Zero();
  68142. }
  68143. SphericalPolynomial.prototype.addAmbient = function (color) {
  68144. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68145. this.xx = this.xx.add(colorVector);
  68146. this.yy = this.yy.add(colorVector);
  68147. this.zz = this.zz.add(colorVector);
  68148. };
  68149. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  68150. var result = new SphericalPolynomial();
  68151. result.x = harmonics.L11.scale(1.02333);
  68152. result.y = harmonics.L1_1.scale(1.02333);
  68153. result.z = harmonics.L10.scale(1.02333);
  68154. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  68155. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  68156. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  68157. result.yz = harmonics.L2_1.scale(0.858086);
  68158. result.zx = harmonics.L21.scale(0.858086);
  68159. result.xy = harmonics.L2_2.scale(0.858086);
  68160. result.scale(1.0 / Math.PI);
  68161. return result;
  68162. };
  68163. SphericalPolynomial.prototype.scale = function (scale) {
  68164. this.x = this.x.scale(scale);
  68165. this.y = this.y.scale(scale);
  68166. this.z = this.z.scale(scale);
  68167. this.xx = this.xx.scale(scale);
  68168. this.yy = this.yy.scale(scale);
  68169. this.zz = this.zz.scale(scale);
  68170. this.yz = this.yz.scale(scale);
  68171. this.zx = this.zx.scale(scale);
  68172. this.xy = this.xy.scale(scale);
  68173. };
  68174. return SphericalPolynomial;
  68175. }());
  68176. BABYLON.SphericalPolynomial = SphericalPolynomial;
  68177. var SphericalHarmonics = /** @class */ (function () {
  68178. function SphericalHarmonics() {
  68179. this.L00 = BABYLON.Vector3.Zero();
  68180. this.L1_1 = BABYLON.Vector3.Zero();
  68181. this.L10 = BABYLON.Vector3.Zero();
  68182. this.L11 = BABYLON.Vector3.Zero();
  68183. this.L2_2 = BABYLON.Vector3.Zero();
  68184. this.L2_1 = BABYLON.Vector3.Zero();
  68185. this.L20 = BABYLON.Vector3.Zero();
  68186. this.L21 = BABYLON.Vector3.Zero();
  68187. this.L22 = BABYLON.Vector3.Zero();
  68188. }
  68189. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  68190. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68191. var c = colorVector.scale(deltaSolidAngle);
  68192. this.L00 = this.L00.add(c.scale(0.282095));
  68193. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  68194. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  68195. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  68196. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  68197. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  68198. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  68199. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  68200. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  68201. };
  68202. SphericalHarmonics.prototype.scale = function (scale) {
  68203. this.L00 = this.L00.scale(scale);
  68204. this.L1_1 = this.L1_1.scale(scale);
  68205. this.L10 = this.L10.scale(scale);
  68206. this.L11 = this.L11.scale(scale);
  68207. this.L2_2 = this.L2_2.scale(scale);
  68208. this.L2_1 = this.L2_1.scale(scale);
  68209. this.L20 = this.L20.scale(scale);
  68210. this.L21 = this.L21.scale(scale);
  68211. this.L22 = this.L22.scale(scale);
  68212. };
  68213. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  68214. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  68215. //
  68216. // E_lm = A_l * L_lm
  68217. //
  68218. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  68219. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  68220. // the scaling factors are given in equation 9.
  68221. // Constant (Band 0)
  68222. this.L00 = this.L00.scale(3.141593);
  68223. // Linear (Band 1)
  68224. this.L1_1 = this.L1_1.scale(2.094395);
  68225. this.L10 = this.L10.scale(2.094395);
  68226. this.L11 = this.L11.scale(2.094395);
  68227. // Quadratic (Band 2)
  68228. this.L2_2 = this.L2_2.scale(0.785398);
  68229. this.L2_1 = this.L2_1.scale(0.785398);
  68230. this.L20 = this.L20.scale(0.785398);
  68231. this.L21 = this.L21.scale(0.785398);
  68232. this.L22 = this.L22.scale(0.785398);
  68233. };
  68234. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  68235. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  68236. // L = (1/pi) * E * rho
  68237. //
  68238. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  68239. this.scale(1.0 / Math.PI);
  68240. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  68241. // (The pixel shader must apply albedo after texture fetches, etc).
  68242. };
  68243. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  68244. var result = new SphericalHarmonics();
  68245. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  68246. result.L1_1 = polynomial.y.scale(0.977204);
  68247. result.L10 = polynomial.z.scale(0.977204);
  68248. result.L11 = polynomial.x.scale(0.977204);
  68249. result.L2_2 = polynomial.xy.scale(1.16538);
  68250. result.L2_1 = polynomial.yz.scale(1.16538);
  68251. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  68252. result.L21 = polynomial.zx.scale(1.16538);
  68253. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  68254. result.scale(Math.PI);
  68255. return result;
  68256. };
  68257. return SphericalHarmonics;
  68258. }());
  68259. BABYLON.SphericalHarmonics = SphericalHarmonics;
  68260. })(BABYLON || (BABYLON = {}));
  68261. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  68262. var BABYLON;
  68263. (function (BABYLON) {
  68264. var FileFaceOrientation = /** @class */ (function () {
  68265. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  68266. this.name = name;
  68267. this.worldAxisForNormal = worldAxisForNormal;
  68268. this.worldAxisForFileX = worldAxisForFileX;
  68269. this.worldAxisForFileY = worldAxisForFileY;
  68270. }
  68271. return FileFaceOrientation;
  68272. }());
  68273. ;
  68274. /**
  68275. * Helper class dealing with the extraction of spherical polynomial dataArray
  68276. * from a cube map.
  68277. */
  68278. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  68279. function CubeMapToSphericalPolynomialTools() {
  68280. }
  68281. /**
  68282. * Converts a texture to the according Spherical Polynomial data.
  68283. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68284. *
  68285. * @param texture The texture to extract the information from.
  68286. * @return The Spherical Polynomial data.
  68287. */
  68288. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  68289. if (!texture.isCube) {
  68290. // Only supports cube Textures currently.
  68291. return null;
  68292. }
  68293. var size = texture.getSize().width;
  68294. var right = texture.readPixels(0);
  68295. var left = texture.readPixels(1);
  68296. var up;
  68297. var down;
  68298. if (texture.isRenderTarget) {
  68299. up = texture.readPixels(3);
  68300. down = texture.readPixels(2);
  68301. }
  68302. else {
  68303. up = texture.readPixels(2);
  68304. down = texture.readPixels(3);
  68305. }
  68306. var front = texture.readPixels(4);
  68307. var back = texture.readPixels(5);
  68308. var gammaSpace = texture.gammaSpace;
  68309. // Always read as RGBA.
  68310. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  68311. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68312. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68313. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68314. }
  68315. var cubeInfo = {
  68316. size: size,
  68317. right: right,
  68318. left: left,
  68319. up: up,
  68320. down: down,
  68321. front: front,
  68322. back: back,
  68323. format: format,
  68324. type: type,
  68325. gammaSpace: gammaSpace,
  68326. };
  68327. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  68328. };
  68329. /**
  68330. * Converts a cubemap to the according Spherical Polynomial data.
  68331. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68332. *
  68333. * @param cubeInfo The Cube map to extract the information from.
  68334. * @return The Spherical Polynomial data.
  68335. */
  68336. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  68337. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  68338. var totalSolidAngle = 0.0;
  68339. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  68340. var du = 2.0 / cubeInfo.size;
  68341. var dv = du;
  68342. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  68343. var minUV = du * 0.5 - 1.0;
  68344. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68345. var fileFace = this.FileFaces[faceIndex];
  68346. var dataArray = cubeInfo[fileFace.name];
  68347. var v = minUV;
  68348. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  68349. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  68350. // Because SP is still linear, so summation is fine in that basis.
  68351. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  68352. for (var y = 0; y < cubeInfo.size; y++) {
  68353. var u = minUV;
  68354. for (var x = 0; x < cubeInfo.size; x++) {
  68355. // World direction (not normalised)
  68356. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  68357. worldDirection.normalize();
  68358. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  68359. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  68360. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  68361. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  68362. // Handle Integer types.
  68363. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68364. r /= 255;
  68365. g /= 255;
  68366. b /= 255;
  68367. }
  68368. // Handle Gamma space textures.
  68369. if (cubeInfo.gammaSpace) {
  68370. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  68371. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  68372. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  68373. }
  68374. var color = new BABYLON.Color3(r, g, b);
  68375. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  68376. totalSolidAngle += deltaSolidAngle;
  68377. u += du;
  68378. }
  68379. v += dv;
  68380. }
  68381. }
  68382. // Solid angle for entire sphere is 4*pi
  68383. var sphereSolidAngle = 4.0 * Math.PI;
  68384. // Adjust the solid angle to allow for how many faces we processed.
  68385. var facesProcessed = 6.0;
  68386. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  68387. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  68388. // This is needed because the numerical integration over the cube uses a
  68389. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  68390. // and also to compensate for accumulative error due to float precision in the summation.
  68391. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  68392. sphericalHarmonics.scale(correctionFactor);
  68393. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  68394. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  68395. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  68396. };
  68397. CubeMapToSphericalPolynomialTools.FileFaces = [
  68398. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  68399. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  68400. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  68401. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  68402. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  68403. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  68404. ];
  68405. return CubeMapToSphericalPolynomialTools;
  68406. }());
  68407. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  68408. })(BABYLON || (BABYLON = {}));
  68409. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  68410. var BABYLON;
  68411. (function (BABYLON) {
  68412. /**
  68413. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  68414. */
  68415. var PanoramaToCubeMapTools = /** @class */ (function () {
  68416. function PanoramaToCubeMapTools() {
  68417. }
  68418. /**
  68419. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  68420. *
  68421. * @param float32Array The source data.
  68422. * @param inputWidth The width of the input panorama.
  68423. * @param inputhHeight The height of the input panorama.
  68424. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  68425. * @return The cubemap data
  68426. */
  68427. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  68428. if (!float32Array) {
  68429. throw "ConvertPanoramaToCubemap: input cannot be null";
  68430. }
  68431. if (float32Array.length != inputWidth * inputHeight * 3) {
  68432. throw "ConvertPanoramaToCubemap: input size is wrong";
  68433. }
  68434. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  68435. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  68436. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  68437. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  68438. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  68439. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  68440. return {
  68441. front: textureFront,
  68442. back: textureBack,
  68443. left: textureLeft,
  68444. right: textureRight,
  68445. up: textureUp,
  68446. down: textureDown,
  68447. size: size,
  68448. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  68449. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  68450. gammaSpace: false,
  68451. };
  68452. };
  68453. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  68454. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  68455. var textureArray = new Float32Array(buffer);
  68456. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  68457. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  68458. var dy = 1 / texSize;
  68459. var fy = 0;
  68460. for (var y = 0; y < texSize; y++) {
  68461. var xv1 = faceData[0];
  68462. var xv2 = faceData[2];
  68463. for (var x = 0; x < texSize; x++) {
  68464. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  68465. v.normalize();
  68466. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  68467. // 3 channels per pixels
  68468. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  68469. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  68470. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  68471. xv1 = xv1.add(rotDX1);
  68472. xv2 = xv2.add(rotDX2);
  68473. }
  68474. fy += dy;
  68475. }
  68476. return textureArray;
  68477. };
  68478. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  68479. var theta = Math.atan2(vDir.z, vDir.x);
  68480. var phi = Math.acos(vDir.y);
  68481. while (theta < -Math.PI)
  68482. theta += 2 * Math.PI;
  68483. while (theta > Math.PI)
  68484. theta -= 2 * Math.PI;
  68485. var dx = theta / Math.PI;
  68486. var dy = phi / Math.PI;
  68487. // recenter.
  68488. dx = dx * 0.5 + 0.5;
  68489. var px = Math.round(dx * inputWidth);
  68490. if (px < 0)
  68491. px = 0;
  68492. else if (px >= inputWidth)
  68493. px = inputWidth - 1;
  68494. var py = Math.round(dy * inputHeight);
  68495. if (py < 0)
  68496. py = 0;
  68497. else if (py >= inputHeight)
  68498. py = inputHeight - 1;
  68499. var inputY = (inputHeight - py - 1);
  68500. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  68501. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  68502. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  68503. return {
  68504. r: r,
  68505. g: g,
  68506. b: b
  68507. };
  68508. };
  68509. PanoramaToCubeMapTools.FACE_FRONT = [
  68510. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68511. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68512. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68513. new BABYLON.Vector3(1.0, 1.0, -1.0)
  68514. ];
  68515. PanoramaToCubeMapTools.FACE_BACK = [
  68516. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68517. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68518. new BABYLON.Vector3(1.0, 1.0, 1.0),
  68519. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  68520. ];
  68521. PanoramaToCubeMapTools.FACE_RIGHT = [
  68522. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68523. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68524. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68525. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68526. ];
  68527. PanoramaToCubeMapTools.FACE_LEFT = [
  68528. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68529. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68530. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68531. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  68532. ];
  68533. PanoramaToCubeMapTools.FACE_DOWN = [
  68534. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68535. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68536. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68537. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68538. ];
  68539. PanoramaToCubeMapTools.FACE_UP = [
  68540. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68541. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68542. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68543. new BABYLON.Vector3(1.0, -1.0, -1.0)
  68544. ];
  68545. return PanoramaToCubeMapTools;
  68546. }());
  68547. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  68548. })(BABYLON || (BABYLON = {}));
  68549. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  68550. var BABYLON;
  68551. (function (BABYLON) {
  68552. ;
  68553. /**
  68554. * This groups tools to convert HDR texture to native colors array.
  68555. */
  68556. var HDRTools = /** @class */ (function () {
  68557. function HDRTools() {
  68558. }
  68559. HDRTools.Ldexp = function (mantissa, exponent) {
  68560. if (exponent > 1023) {
  68561. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  68562. }
  68563. if (exponent < -1074) {
  68564. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  68565. }
  68566. return mantissa * Math.pow(2, exponent);
  68567. };
  68568. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  68569. if (exponent > 0) {
  68570. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  68571. float32array[index + 0] = red * exponent;
  68572. float32array[index + 1] = green * exponent;
  68573. float32array[index + 2] = blue * exponent;
  68574. }
  68575. else {
  68576. float32array[index + 0] = 0;
  68577. float32array[index + 1] = 0;
  68578. float32array[index + 2] = 0;
  68579. }
  68580. };
  68581. HDRTools.readStringLine = function (uint8array, startIndex) {
  68582. var line = "";
  68583. var character = "";
  68584. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  68585. character = String.fromCharCode(uint8array[i]);
  68586. if (character == "\n") {
  68587. break;
  68588. }
  68589. line += character;
  68590. }
  68591. return line;
  68592. };
  68593. /**
  68594. * Reads header information from an RGBE texture stored in a native array.
  68595. * More information on this format are available here:
  68596. * https://en.wikipedia.org/wiki/RGBE_image_format
  68597. *
  68598. * @param uint8array The binary file stored in native array.
  68599. * @return The header information.
  68600. */
  68601. HDRTools.RGBE_ReadHeader = function (uint8array) {
  68602. var height = 0;
  68603. var width = 0;
  68604. var line = this.readStringLine(uint8array, 0);
  68605. if (line[0] != '#' || line[1] != '?') {
  68606. throw "Bad HDR Format.";
  68607. }
  68608. var endOfHeader = false;
  68609. var findFormat = false;
  68610. var lineIndex = 0;
  68611. do {
  68612. lineIndex += (line.length + 1);
  68613. line = this.readStringLine(uint8array, lineIndex);
  68614. if (line == "FORMAT=32-bit_rle_rgbe") {
  68615. findFormat = true;
  68616. }
  68617. else if (line.length == 0) {
  68618. endOfHeader = true;
  68619. }
  68620. } while (!endOfHeader);
  68621. if (!findFormat) {
  68622. throw "HDR Bad header format, unsupported FORMAT";
  68623. }
  68624. lineIndex += (line.length + 1);
  68625. line = this.readStringLine(uint8array, lineIndex);
  68626. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  68627. var match = sizeRegexp.exec(line);
  68628. // TODO. Support +Y and -X if needed.
  68629. if (!match || match.length < 3) {
  68630. throw "HDR Bad header format, no size";
  68631. }
  68632. width = parseInt(match[2]);
  68633. height = parseInt(match[1]);
  68634. if (width < 8 || width > 0x7fff) {
  68635. throw "HDR Bad header format, unsupported size";
  68636. }
  68637. lineIndex += (line.length + 1);
  68638. return {
  68639. height: height,
  68640. width: width,
  68641. dataPosition: lineIndex
  68642. };
  68643. };
  68644. /**
  68645. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  68646. * This RGBE texture needs to store the information as a panorama.
  68647. *
  68648. * More information on this format are available here:
  68649. * https://en.wikipedia.org/wiki/RGBE_image_format
  68650. *
  68651. * @param buffer The binary file stored in an array buffer.
  68652. * @param size The expected size of the extracted cubemap.
  68653. * @return The Cube Map information.
  68654. */
  68655. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  68656. var uint8array = new Uint8Array(buffer);
  68657. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  68658. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68659. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  68660. return cubeMapData;
  68661. };
  68662. /**
  68663. * Returns the pixels data extracted from an RGBE texture.
  68664. * This pixels will be stored left to right up to down in the R G B order in one array.
  68665. *
  68666. * More information on this format are available here:
  68667. * https://en.wikipedia.org/wiki/RGBE_image_format
  68668. *
  68669. * @param uint8array The binary file stored in an array buffer.
  68670. * @param hdrInfo The header information of the file.
  68671. * @return The pixels data in RGB right to left up to down order.
  68672. */
  68673. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  68674. // Keep for multi format supports.
  68675. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68676. };
  68677. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  68678. var num_scanlines = hdrInfo.height;
  68679. var scanline_width = hdrInfo.width;
  68680. var a, b, c, d, count;
  68681. var dataIndex = hdrInfo.dataPosition;
  68682. var index = 0, endIndex = 0, i = 0;
  68683. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  68684. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  68685. // 3 channels of 4 bytes per pixel in float.
  68686. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  68687. var resultArray = new Float32Array(resultBuffer);
  68688. // read in each successive scanline
  68689. while (num_scanlines > 0) {
  68690. a = uint8array[dataIndex++];
  68691. b = uint8array[dataIndex++];
  68692. c = uint8array[dataIndex++];
  68693. d = uint8array[dataIndex++];
  68694. if (a != 2 || b != 2 || (c & 0x80)) {
  68695. // this file is not run length encoded
  68696. throw "HDR Bad header format, not RLE";
  68697. }
  68698. if (((c << 8) | d) != scanline_width) {
  68699. throw "HDR Bad header format, wrong scan line width";
  68700. }
  68701. index = 0;
  68702. // read each of the four channels for the scanline into the buffer
  68703. for (i = 0; i < 4; i++) {
  68704. endIndex = (i + 1) * scanline_width;
  68705. while (index < endIndex) {
  68706. a = uint8array[dataIndex++];
  68707. b = uint8array[dataIndex++];
  68708. if (a > 128) {
  68709. // a run of the same value
  68710. count = a - 128;
  68711. if ((count == 0) || (count > endIndex - index)) {
  68712. throw "HDR Bad Format, bad scanline data (run)";
  68713. }
  68714. while (count-- > 0) {
  68715. scanLineArray[index++] = b;
  68716. }
  68717. }
  68718. else {
  68719. // a non-run
  68720. count = a;
  68721. if ((count == 0) || (count > endIndex - index)) {
  68722. throw "HDR Bad Format, bad scanline data (non-run)";
  68723. }
  68724. scanLineArray[index++] = b;
  68725. if (--count > 0) {
  68726. for (var j = 0; j < count; j++) {
  68727. scanLineArray[index++] = uint8array[dataIndex++];
  68728. }
  68729. }
  68730. }
  68731. }
  68732. }
  68733. // now convert data from buffer into floats
  68734. for (i = 0; i < scanline_width; i++) {
  68735. a = scanLineArray[i];
  68736. b = scanLineArray[i + scanline_width];
  68737. c = scanLineArray[i + 2 * scanline_width];
  68738. d = scanLineArray[i + 3 * scanline_width];
  68739. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  68740. }
  68741. num_scanlines--;
  68742. }
  68743. return resultArray;
  68744. };
  68745. return HDRTools;
  68746. }());
  68747. BABYLON.HDRTools = HDRTools;
  68748. })(BABYLON || (BABYLON = {}));
  68749. //# sourceMappingURL=babylon.hdr.js.map
  68750. var BABYLON;
  68751. (function (BABYLON) {
  68752. /**
  68753. * This represents a texture coming from an HDR input.
  68754. *
  68755. * The only supported format is currently panorama picture stored in RGBE format.
  68756. * Example of such files can be found on HDRLib: http://hdrlib.com/
  68757. */
  68758. var HDRCubeTexture = /** @class */ (function (_super) {
  68759. __extends(HDRCubeTexture, _super);
  68760. /**
  68761. * Instantiates an HDRTexture from the following parameters.
  68762. *
  68763. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  68764. * @param scene The scene the texture will be used in
  68765. * @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.
  68766. * @param noMipmap Forces to not generate the mipmap if true
  68767. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  68768. * @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)
  68769. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  68770. */
  68771. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  68772. if (noMipmap === void 0) { noMipmap = false; }
  68773. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68774. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68775. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68776. if (onLoad === void 0) { onLoad = null; }
  68777. if (onError === void 0) { onError = null; }
  68778. var _this = _super.call(this, scene) || this;
  68779. _this._useInGammaSpace = false;
  68780. _this._generateHarmonics = true;
  68781. _this._isBABYLONPreprocessed = false;
  68782. _this._onLoad = null;
  68783. _this._onError = null;
  68784. /**
  68785. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  68786. */
  68787. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  68788. /**
  68789. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  68790. * This is usefull at run time to apply the good shader.
  68791. */
  68792. _this.isPMREM = false;
  68793. _this._isBlocking = true;
  68794. if (!url) {
  68795. return _this;
  68796. }
  68797. _this.name = url;
  68798. _this.url = url;
  68799. _this.hasAlpha = false;
  68800. _this.isCube = true;
  68801. _this._textureMatrix = BABYLON.Matrix.Identity();
  68802. _this._onLoad = onLoad;
  68803. _this._onError = onError;
  68804. _this.gammaSpace = false;
  68805. var caps = scene.getEngine().getCaps();
  68806. if (size) {
  68807. _this._isBABYLONPreprocessed = false;
  68808. _this._noMipmap = noMipmap;
  68809. _this._size = size;
  68810. _this._useInGammaSpace = useInGammaSpace;
  68811. _this._usePMREMGenerator = usePMREMGenerator &&
  68812. caps.textureLOD &&
  68813. caps.textureFloat &&
  68814. !_this._useInGammaSpace;
  68815. }
  68816. else {
  68817. _this._isBABYLONPreprocessed = true;
  68818. _this._noMipmap = false;
  68819. _this._useInGammaSpace = false;
  68820. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  68821. !_this._useInGammaSpace;
  68822. }
  68823. _this.isPMREM = _this._usePMREMGenerator;
  68824. _this._texture = _this._getFromCache(url, _this._noMipmap);
  68825. if (!_this._texture) {
  68826. if (!scene.useDelayedTextureLoading) {
  68827. _this.loadTexture();
  68828. }
  68829. else {
  68830. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68831. }
  68832. }
  68833. return _this;
  68834. }
  68835. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  68836. /**
  68837. * Gets wether or not the texture is blocking during loading.
  68838. */
  68839. get: function () {
  68840. return this._isBlocking;
  68841. },
  68842. /**
  68843. * Sets wether or not the texture is blocking during loading.
  68844. */
  68845. set: function (value) {
  68846. this._isBlocking = value;
  68847. },
  68848. enumerable: true,
  68849. configurable: true
  68850. });
  68851. /**
  68852. * Occurs when the file is a preprocessed .babylon.hdr file.
  68853. */
  68854. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  68855. var _this = this;
  68856. var mipLevels = 0;
  68857. var floatArrayView = null;
  68858. var scene = this.getScene();
  68859. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  68860. var mips = new Array();
  68861. if (!floatArrayView) {
  68862. return mips;
  68863. }
  68864. var startIndex = 30;
  68865. for (var level = 0; level < mipLevels; level++) {
  68866. mips.push([]);
  68867. // Fill each pixel of the mip level.
  68868. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  68869. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68870. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  68871. mips[level].push(faceData);
  68872. startIndex += faceSize;
  68873. }
  68874. }
  68875. return mips;
  68876. } : null;
  68877. var callback = function (buffer) {
  68878. var scene = _this.getScene();
  68879. if (!scene) {
  68880. return null;
  68881. }
  68882. // Create Native Array Views
  68883. var intArrayView = new Int32Array(buffer);
  68884. floatArrayView = new Float32Array(buffer);
  68885. // Fill header.
  68886. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  68887. _this._size = intArrayView[1]; // CubeMap max mip face size.
  68888. // Update Texture Information.
  68889. if (!_this._texture) {
  68890. return null;
  68891. }
  68892. _this._texture.updateSize(_this._size, _this._size);
  68893. // Fill polynomial information.
  68894. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  68895. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  68896. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  68897. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  68898. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  68899. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  68900. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  68901. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  68902. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  68903. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  68904. _this.sphericalPolynomial = sphericalPolynomial;
  68905. // Fill pixel data.
  68906. mipLevels = intArrayView[29]; // Number of mip levels.
  68907. var startIndex = 30;
  68908. var data = [];
  68909. var faceSize = Math.pow(_this._size, 2) * 3;
  68910. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68911. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  68912. startIndex += faceSize;
  68913. }
  68914. var results = [];
  68915. var byteArray = null;
  68916. // Push each faces.
  68917. for (var k = 0; k < 6; k++) {
  68918. var dataFace = null;
  68919. // To be deprecated.
  68920. if (version === 1) {
  68921. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  68922. dataFace = data[j];
  68923. }
  68924. // If special cases.
  68925. if (!mipmapGenerator && dataFace) {
  68926. if (!scene.getEngine().getCaps().textureFloat) {
  68927. // 3 channels of 1 bytes per pixel in bytes.
  68928. var byteBuffer = new ArrayBuffer(faceSize);
  68929. byteArray = new Uint8Array(byteBuffer);
  68930. }
  68931. for (var i = 0; i < _this._size * _this._size; i++) {
  68932. // Put in gamma space if requested.
  68933. if (_this._useInGammaSpace) {
  68934. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68935. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68936. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68937. }
  68938. // Convert to int texture for fallback.
  68939. if (byteArray) {
  68940. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68941. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68942. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68943. // May use luminance instead if the result is not accurate.
  68944. var max = Math.max(Math.max(r, g), b);
  68945. if (max > 255) {
  68946. var scale = 255 / max;
  68947. r *= scale;
  68948. g *= scale;
  68949. b *= scale;
  68950. }
  68951. byteArray[(i * 3) + 0] = r;
  68952. byteArray[(i * 3) + 1] = g;
  68953. byteArray[(i * 3) + 2] = b;
  68954. }
  68955. }
  68956. }
  68957. // Fill the array accordingly.
  68958. if (byteArray) {
  68959. results.push(byteArray);
  68960. }
  68961. else {
  68962. results.push(dataFace);
  68963. }
  68964. }
  68965. return results;
  68966. };
  68967. if (scene) {
  68968. 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);
  68969. }
  68970. };
  68971. /**
  68972. * Occurs when the file is raw .hdr file.
  68973. */
  68974. HDRCubeTexture.prototype.loadHDRTexture = function () {
  68975. var _this = this;
  68976. var callback = function (buffer) {
  68977. var scene = _this.getScene();
  68978. if (!scene) {
  68979. return null;
  68980. }
  68981. // Extract the raw linear data.
  68982. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  68983. // Generate harmonics if needed.
  68984. if (_this._generateHarmonics) {
  68985. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  68986. _this.sphericalPolynomial = sphericalPolynomial;
  68987. }
  68988. var results = [];
  68989. var byteArray = null;
  68990. // Push each faces.
  68991. for (var j = 0; j < 6; j++) {
  68992. // Create uintarray fallback.
  68993. if (!scene.getEngine().getCaps().textureFloat) {
  68994. // 3 channels of 1 bytes per pixel in bytes.
  68995. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  68996. byteArray = new Uint8Array(byteBuffer);
  68997. }
  68998. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  68999. // If special cases.
  69000. if (_this._useInGammaSpace || byteArray) {
  69001. for (var i = 0; i < _this._size * _this._size; i++) {
  69002. // Put in gamma space if requested.
  69003. if (_this._useInGammaSpace) {
  69004. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69005. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69006. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69007. }
  69008. // Convert to int texture for fallback.
  69009. if (byteArray) {
  69010. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69011. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69012. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69013. // May use luminance instead if the result is not accurate.
  69014. var max = Math.max(Math.max(r, g), b);
  69015. if (max > 255) {
  69016. var scale = 255 / max;
  69017. r *= scale;
  69018. g *= scale;
  69019. b *= scale;
  69020. }
  69021. byteArray[(i * 3) + 0] = r;
  69022. byteArray[(i * 3) + 1] = g;
  69023. byteArray[(i * 3) + 2] = b;
  69024. }
  69025. }
  69026. }
  69027. if (byteArray) {
  69028. results.push(byteArray);
  69029. }
  69030. else {
  69031. results.push(dataFace);
  69032. }
  69033. }
  69034. return results;
  69035. };
  69036. var mipmapGenerator = null;
  69037. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  69038. // if (!this._noMipmap &&
  69039. // this._usePMREMGenerator) {
  69040. // mipmapGenerator = (data: ArrayBufferView[]) => {
  69041. // // Custom setup of the generator matching with the PBR shader values.
  69042. // var generator = new BABYLON.PMREMGenerator(data,
  69043. // this._size,
  69044. // this._size,
  69045. // 0,
  69046. // 3,
  69047. // this.getScene().getEngine().getCaps().textureFloat,
  69048. // 2048,
  69049. // 0.25,
  69050. // false,
  69051. // true);
  69052. // return generator.filterCubeMap();
  69053. // };
  69054. // }
  69055. var scene = this.getScene();
  69056. if (scene) {
  69057. 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);
  69058. }
  69059. };
  69060. /**
  69061. * Starts the loading process of the texture.
  69062. */
  69063. HDRCubeTexture.prototype.loadTexture = function () {
  69064. if (this._isBABYLONPreprocessed) {
  69065. this.loadBabylonTexture();
  69066. }
  69067. else {
  69068. this.loadHDRTexture();
  69069. }
  69070. };
  69071. HDRCubeTexture.prototype.clone = function () {
  69072. var scene = this.getScene();
  69073. if (!scene) {
  69074. return this;
  69075. }
  69076. var size = (this._isBABYLONPreprocessed ? null : this._size);
  69077. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  69078. // Base texture
  69079. newTexture.level = this.level;
  69080. newTexture.wrapU = this.wrapU;
  69081. newTexture.wrapV = this.wrapV;
  69082. newTexture.coordinatesIndex = this.coordinatesIndex;
  69083. newTexture.coordinatesMode = this.coordinatesMode;
  69084. return newTexture;
  69085. };
  69086. // Methods
  69087. HDRCubeTexture.prototype.delayLoad = function () {
  69088. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69089. return;
  69090. }
  69091. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69092. this._texture = this._getFromCache(this.url, this._noMipmap);
  69093. if (!this._texture) {
  69094. this.loadTexture();
  69095. }
  69096. };
  69097. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  69098. return this._textureMatrix;
  69099. };
  69100. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69101. this._textureMatrix = value;
  69102. };
  69103. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69104. var texture = null;
  69105. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  69106. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  69107. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  69108. texture.name = parsedTexture.name;
  69109. texture.hasAlpha = parsedTexture.hasAlpha;
  69110. texture.level = parsedTexture.level;
  69111. texture.coordinatesMode = parsedTexture.coordinatesMode;
  69112. texture.isBlocking = parsedTexture.isBlocking;
  69113. }
  69114. return texture;
  69115. };
  69116. HDRCubeTexture.prototype.serialize = function () {
  69117. if (!this.name) {
  69118. return null;
  69119. }
  69120. var serializationObject = {};
  69121. serializationObject.name = this.name;
  69122. serializationObject.hasAlpha = this.hasAlpha;
  69123. serializationObject.isCube = true;
  69124. serializationObject.level = this.level;
  69125. serializationObject.size = this._size;
  69126. serializationObject.coordinatesMode = this.coordinatesMode;
  69127. serializationObject.useInGammaSpace = this._useInGammaSpace;
  69128. serializationObject.generateHarmonics = this._generateHarmonics;
  69129. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  69130. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  69131. serializationObject.customType = "BABYLON.HDRCubeTexture";
  69132. serializationObject.noMipmap = this._noMipmap;
  69133. serializationObject.isBlocking = this._isBlocking;
  69134. return serializationObject;
  69135. };
  69136. /**
  69137. * Saves as a file the data contained in the texture in a binary format.
  69138. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69139. * as the spherical used in the lighting.
  69140. * @param url The HDR file url.
  69141. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69142. * @param onError Method called if any error happens during download.
  69143. * @return The packed binary data.
  69144. */
  69145. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  69146. if (onError === void 0) { onError = null; }
  69147. var callback = function (buffer) {
  69148. var data = new Blob([buffer], { type: 'application/octet-stream' });
  69149. // Returns a URL you can use as a href.
  69150. var objUrl = window.URL.createObjectURL(data);
  69151. // Simulates a link to it and click to dowload.
  69152. var a = document.createElement("a");
  69153. document.body.appendChild(a);
  69154. a.style.display = "none";
  69155. a.href = objUrl;
  69156. a.download = "envmap.babylon.hdr";
  69157. a.click();
  69158. };
  69159. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  69160. };
  69161. /**
  69162. * Serializes the data contained in the texture in a binary format.
  69163. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69164. * as the spherical used in the lighting.
  69165. * @param url The HDR file url.
  69166. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69167. * @param onError Method called if any error happens during download.
  69168. * @return The packed binary data.
  69169. */
  69170. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  69171. if (onError === void 0) { onError = null; }
  69172. // Needs the url tho create the texture.
  69173. if (!url) {
  69174. return;
  69175. }
  69176. // Check Power of two size.
  69177. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  69178. return;
  69179. }
  69180. // Coming Back in 3.x.
  69181. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  69182. };
  69183. HDRCubeTexture._facesMapping = [
  69184. "right",
  69185. "left",
  69186. "up",
  69187. "down",
  69188. "front",
  69189. "back"
  69190. ];
  69191. return HDRCubeTexture;
  69192. }(BABYLON.BaseTexture));
  69193. BABYLON.HDRCubeTexture = HDRCubeTexture;
  69194. })(BABYLON || (BABYLON = {}));
  69195. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  69196. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  69197. // Huge respect for a such great lib.
  69198. // Earcut license:
  69199. // Copyright (c) 2016, Mapbox
  69200. //
  69201. // Permission to use, copy, modify, and/or distribute this software for any purpose
  69202. // with or without fee is hereby granted, provided that the above copyright notice
  69203. // and this permission notice appear in all copies.
  69204. //
  69205. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  69206. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  69207. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  69208. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  69209. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  69210. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  69211. // THIS SOFTWARE.
  69212. var Earcut;
  69213. (function (Earcut) {
  69214. /**
  69215. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  69216. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  69217. * @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).
  69218. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  69219. */
  69220. function earcut(data, holeIndices, dim) {
  69221. dim = dim || 2;
  69222. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  69223. if (!outerNode)
  69224. return triangles;
  69225. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  69226. if (hasHoles)
  69227. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  69228. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  69229. if (data.length > 80 * dim) {
  69230. minX = maxX = data[0];
  69231. minY = maxY = data[1];
  69232. for (var i = dim; i < outerLen; i += dim) {
  69233. x = data[i];
  69234. y = data[i + 1];
  69235. if (x < minX)
  69236. minX = x;
  69237. if (y < minY)
  69238. minY = y;
  69239. if (x > maxX)
  69240. maxX = x;
  69241. if (y > maxY)
  69242. maxY = y;
  69243. }
  69244. // minX, minY and size are later used to transform coords into integers for z-order calculation
  69245. size = Math.max(maxX - minX, maxY - minY);
  69246. }
  69247. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  69248. return triangles;
  69249. }
  69250. Earcut.earcut = earcut;
  69251. var Node = /** @class */ (function () {
  69252. function Node(i, x, y) {
  69253. this.i = i;
  69254. this.x = x;
  69255. this.y = y;
  69256. this.prev = null;
  69257. this.next = null;
  69258. this.z = null;
  69259. this.prevZ = null;
  69260. this.nextZ = null;
  69261. this.steiner = false;
  69262. }
  69263. return Node;
  69264. }());
  69265. // create a circular doubly linked list from polygon points in the specified winding order
  69266. function linkedList(data, start, end, dim, clockwise) {
  69267. var i, last = null;
  69268. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  69269. for (i = start; i < end; i += dim)
  69270. last = insertNode(i, data[i], data[i + 1], last);
  69271. }
  69272. else {
  69273. for (i = end - dim; i >= start; i -= dim)
  69274. last = insertNode(i, data[i], data[i + 1], last);
  69275. }
  69276. if (last && equals(last, last.next)) {
  69277. removeNode(last);
  69278. last = last.next;
  69279. }
  69280. return last;
  69281. }
  69282. // eliminate colinear or duplicate points
  69283. function filterPoints(start, end) {
  69284. if (!start)
  69285. return start;
  69286. if (!end)
  69287. end = start;
  69288. var p = start, again;
  69289. do {
  69290. again = false;
  69291. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  69292. removeNode(p);
  69293. p = end = p.prev;
  69294. if (p === p.next)
  69295. return undefined;
  69296. again = true;
  69297. }
  69298. else {
  69299. p = p.next;
  69300. }
  69301. } while (again || p !== end);
  69302. return end;
  69303. }
  69304. // main ear slicing loop which triangulates a polygon (given as a linked list)
  69305. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  69306. if (!ear)
  69307. return;
  69308. // interlink polygon nodes in z-order
  69309. if (!pass && size)
  69310. indexCurve(ear, minX, minY, size);
  69311. var stop = ear, prev, next;
  69312. // iterate through ears, slicing them one by one
  69313. while (ear.prev !== ear.next) {
  69314. prev = ear.prev;
  69315. next = ear.next;
  69316. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  69317. // cut off the triangle
  69318. triangles.push(prev.i / dim);
  69319. triangles.push(ear.i / dim);
  69320. triangles.push(next.i / dim);
  69321. removeNode(ear);
  69322. // skipping the next vertice leads to less sliver triangles
  69323. ear = next.next;
  69324. stop = next.next;
  69325. continue;
  69326. }
  69327. ear = next;
  69328. // if we looped through the whole remaining polygon and can't find any more ears
  69329. if (ear === stop) {
  69330. // try filtering points and slicing again
  69331. if (!pass) {
  69332. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  69333. // if this didn't work, try curing all small self-intersections locally
  69334. }
  69335. else if (pass === 1) {
  69336. ear = cureLocalIntersections(ear, triangles, dim);
  69337. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  69338. // as a last resort, try splitting the remaining polygon into two
  69339. }
  69340. else if (pass === 2) {
  69341. splitEarcut(ear, triangles, dim, minX, minY, size);
  69342. }
  69343. break;
  69344. }
  69345. }
  69346. }
  69347. // check whether a polygon node forms a valid ear with adjacent nodes
  69348. function isEar(ear) {
  69349. var a = ear.prev, b = ear, c = ear.next;
  69350. if (area(a, b, c) >= 0)
  69351. return false; // reflex, can't be an ear
  69352. // now make sure we don't have other points inside the potential ear
  69353. var p = ear.next.next;
  69354. while (p !== ear.prev) {
  69355. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69356. area(p.prev, p, p.next) >= 0)
  69357. return false;
  69358. p = p.next;
  69359. }
  69360. return true;
  69361. }
  69362. function isEarHashed(ear, minX, minY, size) {
  69363. var a = ear.prev, b = ear, c = ear.next;
  69364. if (area(a, b, c) >= 0)
  69365. return false; // reflex, can't be an ear
  69366. // triangle bbox; min & max are calculated like this for speed
  69367. 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);
  69368. // z-order range for the current triangle bbox;
  69369. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  69370. // first look for points inside the triangle in increasing z-order
  69371. var p = ear.nextZ;
  69372. while (p && p.z <= maxZ) {
  69373. if (p !== ear.prev &&
  69374. p !== ear.next &&
  69375. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69376. area(p.prev, p, p.next) >= 0)
  69377. return false;
  69378. p = p.nextZ;
  69379. }
  69380. // then look for points in decreasing z-order
  69381. p = ear.prevZ;
  69382. while (p && p.z >= minZ) {
  69383. if (p !== ear.prev &&
  69384. p !== ear.next &&
  69385. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69386. area(p.prev, p, p.next) >= 0)
  69387. return false;
  69388. p = p.prevZ;
  69389. }
  69390. return true;
  69391. }
  69392. // go through all polygon nodes and cure small local self-intersections
  69393. function cureLocalIntersections(start, triangles, dim) {
  69394. var p = start;
  69395. do {
  69396. var a = p.prev, b = p.next.next;
  69397. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  69398. triangles.push(a.i / dim);
  69399. triangles.push(p.i / dim);
  69400. triangles.push(b.i / dim);
  69401. // remove two nodes involved
  69402. removeNode(p);
  69403. removeNode(p.next);
  69404. p = start = b;
  69405. }
  69406. p = p.next;
  69407. } while (p !== start);
  69408. return p;
  69409. }
  69410. // try splitting polygon into two and triangulate them independently
  69411. function splitEarcut(start, triangles, dim, minX, minY, size) {
  69412. // look for a valid diagonal that divides the polygon into two
  69413. var a = start;
  69414. do {
  69415. var b = a.next.next;
  69416. while (b !== a.prev) {
  69417. if (a.i !== b.i && isValidDiagonal(a, b)) {
  69418. // split the polygon in two by the diagonal
  69419. var c = splitPolygon(a, b);
  69420. // filter colinear points around the cuts
  69421. a = filterPoints(a, a.next);
  69422. c = filterPoints(c, c.next);
  69423. // run earcut on each half
  69424. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  69425. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  69426. return;
  69427. }
  69428. b = b.next;
  69429. }
  69430. a = a.next;
  69431. } while (a !== start);
  69432. }
  69433. // link every hole into the outer loop, producing a single-ring polygon without holes
  69434. function eliminateHoles(data, holeIndices, outerNode, dim) {
  69435. var queue = [], i, len, start, end, list;
  69436. for (i = 0, len = holeIndices.length; i < len; i++) {
  69437. start = holeIndices[i] * dim;
  69438. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69439. list = linkedList(data, start, end, dim, false);
  69440. if (list === list.next)
  69441. list.steiner = true;
  69442. queue.push(getLeftmost(list));
  69443. }
  69444. queue.sort(compareX);
  69445. // process holes from left to right
  69446. for (i = 0; i < queue.length; i++) {
  69447. eliminateHole(queue[i], outerNode);
  69448. outerNode = filterPoints(outerNode, outerNode.next);
  69449. }
  69450. return outerNode;
  69451. }
  69452. function compareX(a, b) {
  69453. return a.x - b.x;
  69454. }
  69455. // find a bridge between vertices that connects hole with an outer ring and and link it
  69456. function eliminateHole(hole, outerNode) {
  69457. outerNode = findHoleBridge(hole, outerNode);
  69458. if (outerNode) {
  69459. var b = splitPolygon(outerNode, hole);
  69460. filterPoints(b, b.next);
  69461. }
  69462. }
  69463. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  69464. function findHoleBridge(hole, outerNode) {
  69465. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  69466. // find a segment intersected by a ray from the hole's leftmost point to the left;
  69467. // segment's endpoint with lesser x will be potential connection point
  69468. do {
  69469. if (hy <= p.y && hy >= p.next.y) {
  69470. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  69471. if (x <= hx && x > qx) {
  69472. qx = x;
  69473. if (x === hx) {
  69474. if (hy === p.y)
  69475. return p;
  69476. if (hy === p.next.y)
  69477. return p.next;
  69478. }
  69479. m = p.x < p.next.x ? p : p.next;
  69480. }
  69481. }
  69482. p = p.next;
  69483. } while (p !== outerNode);
  69484. if (!m)
  69485. return null;
  69486. if (hx === qx)
  69487. return m.prev; // hole touches outer segment; pick lower endpoint
  69488. // look for points inside the triangle of hole point, segment intersection and endpoint;
  69489. // if there are no points found, we have a valid connection;
  69490. // otherwise choose the point of the minimum angle with the ray as connection point
  69491. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  69492. p = m.next;
  69493. while (p !== stop) {
  69494. if (hx >= p.x &&
  69495. p.x >= mx &&
  69496. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  69497. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  69498. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  69499. m = p;
  69500. tanMin = tan;
  69501. }
  69502. }
  69503. p = p.next;
  69504. }
  69505. return m;
  69506. }
  69507. // interlink polygon nodes in z-order
  69508. function indexCurve(start, minX, minY, size) {
  69509. var p = start;
  69510. do {
  69511. if (p.z === null)
  69512. p.z = zOrder(p.x, p.y, minX, minY, size);
  69513. p.prevZ = p.prev;
  69514. p.nextZ = p.next;
  69515. p = p.next;
  69516. } while (p !== start);
  69517. p.prevZ.nextZ = null;
  69518. p.prevZ = null;
  69519. sortLinked(p);
  69520. }
  69521. // Simon Tatham's linked list merge sort algorithm
  69522. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  69523. function sortLinked(list) {
  69524. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  69525. do {
  69526. p = list;
  69527. list = null;
  69528. tail = null;
  69529. numMerges = 0;
  69530. while (p) {
  69531. numMerges++;
  69532. q = p;
  69533. pSize = 0;
  69534. for (i = 0; i < inSize; i++) {
  69535. pSize++;
  69536. q = q.nextZ;
  69537. if (!q)
  69538. break;
  69539. }
  69540. qSize = inSize;
  69541. while (pSize > 0 || (qSize > 0 && q)) {
  69542. if (pSize === 0) {
  69543. e = q;
  69544. q = q.nextZ;
  69545. qSize--;
  69546. }
  69547. else if (qSize === 0 || !q) {
  69548. e = p;
  69549. p = p.nextZ;
  69550. pSize--;
  69551. }
  69552. else if (p.z <= q.z) {
  69553. e = p;
  69554. p = p.nextZ;
  69555. pSize--;
  69556. }
  69557. else {
  69558. e = q;
  69559. q = q.nextZ;
  69560. qSize--;
  69561. }
  69562. if (tail)
  69563. tail.nextZ = e;
  69564. else
  69565. list = e;
  69566. e.prevZ = tail;
  69567. tail = e;
  69568. }
  69569. p = q;
  69570. }
  69571. tail.nextZ = null;
  69572. inSize *= 2;
  69573. } while (numMerges > 1);
  69574. return list;
  69575. }
  69576. // z-order of a point given coords and size of the data bounding box
  69577. function zOrder(x, y, minX, minY, size) {
  69578. // coords are transformed into non-negative 15-bit integer range
  69579. x = 32767 * (x - minX) / size;
  69580. y = 32767 * (y - minY) / size;
  69581. x = (x | (x << 8)) & 0x00FF00FF;
  69582. x = (x | (x << 4)) & 0x0F0F0F0F;
  69583. x = (x | (x << 2)) & 0x33333333;
  69584. x = (x | (x << 1)) & 0x55555555;
  69585. y = (y | (y << 8)) & 0x00FF00FF;
  69586. y = (y | (y << 4)) & 0x0F0F0F0F;
  69587. y = (y | (y << 2)) & 0x33333333;
  69588. y = (y | (y << 1)) & 0x55555555;
  69589. return x | (y << 1);
  69590. }
  69591. // find the leftmost node of a polygon ring
  69592. function getLeftmost(start) {
  69593. var p = start, leftmost = start;
  69594. do {
  69595. if (p.x < leftmost.x)
  69596. leftmost = p;
  69597. p = p.next;
  69598. } while (p !== start);
  69599. return leftmost;
  69600. }
  69601. // check if a point lies within a convex triangle
  69602. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  69603. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  69604. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  69605. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  69606. }
  69607. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  69608. function isValidDiagonal(a, b) {
  69609. return a.next.i !== b.i &&
  69610. a.prev.i !== b.i &&
  69611. !intersectsPolygon(a, b) &&
  69612. locallyInside(a, b) &&
  69613. locallyInside(b, a) &&
  69614. middleInside(a, b);
  69615. }
  69616. // signed area of a triangle
  69617. function area(p, q, r) {
  69618. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  69619. }
  69620. // check if two points are equal
  69621. function equals(p1, p2) {
  69622. return p1.x === p2.x && p1.y === p2.y;
  69623. }
  69624. // check if two segments intersect
  69625. function intersects(p1, q1, p2, q2) {
  69626. if ((equals(p1, q1) && equals(p2, q2)) ||
  69627. (equals(p1, q2) && equals(p2, q1)))
  69628. return true;
  69629. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  69630. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  69631. }
  69632. // check if a polygon diagonal intersects any polygon segments
  69633. function intersectsPolygon(a, b) {
  69634. var p = a;
  69635. do {
  69636. if (p.i !== a.i &&
  69637. p.next.i !== a.i &&
  69638. p.i !== b.i &&
  69639. p.next.i !== b.i &&
  69640. intersects(p, p.next, a, b))
  69641. return true;
  69642. p = p.next;
  69643. } while (p !== a);
  69644. return false;
  69645. }
  69646. // check if a polygon diagonal is locally inside the polygon
  69647. function locallyInside(a, b) {
  69648. return area(a.prev, a, a.next) < 0
  69649. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  69650. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  69651. }
  69652. // check if the middle point of a polygon diagonal is inside the polygon
  69653. function middleInside(a, b) {
  69654. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  69655. do {
  69656. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  69657. inside = !inside;
  69658. p = p.next;
  69659. } while (p !== a);
  69660. return inside;
  69661. }
  69662. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  69663. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  69664. function splitPolygon(a, b) {
  69665. 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;
  69666. a.next = b;
  69667. b.prev = a;
  69668. a2.next = an;
  69669. an.prev = a2;
  69670. b2.next = a2;
  69671. a2.prev = b2;
  69672. bp.next = b2;
  69673. b2.prev = bp;
  69674. return b2;
  69675. }
  69676. // create a node and optionally link it with previous one (in a circular doubly linked list)
  69677. function insertNode(i, x, y, last) {
  69678. var p = new Node(i, x, y);
  69679. if (!last) {
  69680. p.prev = p;
  69681. p.next = p;
  69682. }
  69683. else {
  69684. p.next = last.next;
  69685. p.prev = last;
  69686. last.next.prev = p;
  69687. last.next = p;
  69688. }
  69689. return p;
  69690. }
  69691. function removeNode(p) {
  69692. p.next.prev = p.prev;
  69693. p.prev.next = p.next;
  69694. if (p.prevZ)
  69695. p.prevZ.nextZ = p.nextZ;
  69696. if (p.nextZ)
  69697. p.nextZ.prevZ = p.prevZ;
  69698. }
  69699. /**
  69700. * return a percentage difference between the polygon area and its triangulation area;
  69701. * used to verify correctness of triangulation
  69702. */
  69703. function deviation(data, holeIndices, dim, triangles) {
  69704. var hasHoles = holeIndices && holeIndices.length;
  69705. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  69706. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  69707. if (hasHoles) {
  69708. for (var i = 0, len = holeIndices.length; i < len; i++) {
  69709. var start = holeIndices[i] * dim;
  69710. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69711. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  69712. }
  69713. }
  69714. var trianglesArea = 0;
  69715. for (i = 0; i < triangles.length; i += 3) {
  69716. var a = triangles[i] * dim;
  69717. var b = triangles[i + 1] * dim;
  69718. var c = triangles[i + 2] * dim;
  69719. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  69720. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  69721. }
  69722. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  69723. }
  69724. Earcut.deviation = deviation;
  69725. ;
  69726. function signedArea(data, start, end, dim) {
  69727. var sum = 0;
  69728. for (var i = start, j = end - dim; i < end; i += dim) {
  69729. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  69730. j = i;
  69731. }
  69732. return sum;
  69733. }
  69734. /**
  69735. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  69736. */
  69737. function flatten(data) {
  69738. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  69739. for (var i = 0; i < data.length; i++) {
  69740. for (var j = 0; j < data[i].length; j++) {
  69741. for (var d = 0; d < dim; d++)
  69742. result.vertices.push(data[i][j][d]);
  69743. }
  69744. if (i > 0) {
  69745. holeIndex += data[i - 1].length;
  69746. result.holes.push(holeIndex);
  69747. }
  69748. }
  69749. return result;
  69750. }
  69751. Earcut.flatten = flatten;
  69752. ;
  69753. })(Earcut || (Earcut = {}));
  69754. //# sourceMappingURL=babylon.earcut.js.map
  69755. var BABYLON;
  69756. (function (BABYLON) {
  69757. var IndexedVector2 = /** @class */ (function (_super) {
  69758. __extends(IndexedVector2, _super);
  69759. function IndexedVector2(original, index) {
  69760. var _this = _super.call(this, original.x, original.y) || this;
  69761. _this.index = index;
  69762. return _this;
  69763. }
  69764. return IndexedVector2;
  69765. }(BABYLON.Vector2));
  69766. var PolygonPoints = /** @class */ (function () {
  69767. function PolygonPoints() {
  69768. this.elements = new Array();
  69769. }
  69770. PolygonPoints.prototype.add = function (originalPoints) {
  69771. var _this = this;
  69772. var result = new Array();
  69773. originalPoints.forEach(function (point) {
  69774. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  69775. var newPoint = new IndexedVector2(point, _this.elements.length);
  69776. result.push(newPoint);
  69777. _this.elements.push(newPoint);
  69778. }
  69779. });
  69780. return result;
  69781. };
  69782. PolygonPoints.prototype.computeBounds = function () {
  69783. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69784. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69785. this.elements.forEach(function (point) {
  69786. // x
  69787. if (point.x < lmin.x) {
  69788. lmin.x = point.x;
  69789. }
  69790. else if (point.x > lmax.x) {
  69791. lmax.x = point.x;
  69792. }
  69793. // y
  69794. if (point.y < lmin.y) {
  69795. lmin.y = point.y;
  69796. }
  69797. else if (point.y > lmax.y) {
  69798. lmax.y = point.y;
  69799. }
  69800. });
  69801. return {
  69802. min: lmin,
  69803. max: lmax,
  69804. width: lmax.x - lmin.x,
  69805. height: lmax.y - lmin.y
  69806. };
  69807. };
  69808. return PolygonPoints;
  69809. }());
  69810. var Polygon = /** @class */ (function () {
  69811. function Polygon() {
  69812. }
  69813. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  69814. return [
  69815. new BABYLON.Vector2(xmin, ymin),
  69816. new BABYLON.Vector2(xmax, ymin),
  69817. new BABYLON.Vector2(xmax, ymax),
  69818. new BABYLON.Vector2(xmin, ymax)
  69819. ];
  69820. };
  69821. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  69822. if (cx === void 0) { cx = 0; }
  69823. if (cy === void 0) { cy = 0; }
  69824. if (numberOfSides === void 0) { numberOfSides = 32; }
  69825. var result = new Array();
  69826. var angle = 0;
  69827. var increment = (Math.PI * 2) / numberOfSides;
  69828. for (var i = 0; i < numberOfSides; i++) {
  69829. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  69830. angle -= increment;
  69831. }
  69832. return result;
  69833. };
  69834. Polygon.Parse = function (input) {
  69835. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  69836. var i, result = [];
  69837. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  69838. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  69839. }
  69840. return result;
  69841. };
  69842. Polygon.StartingAt = function (x, y) {
  69843. return BABYLON.Path2.StartingAt(x, y);
  69844. };
  69845. return Polygon;
  69846. }());
  69847. BABYLON.Polygon = Polygon;
  69848. var PolygonMeshBuilder = /** @class */ (function () {
  69849. function PolygonMeshBuilder(name, contours, scene) {
  69850. this._points = new PolygonPoints();
  69851. this._outlinepoints = new PolygonPoints();
  69852. this._holes = new Array();
  69853. this._epoints = new Array();
  69854. this._eholes = new Array();
  69855. this._name = name;
  69856. this._scene = scene;
  69857. var points;
  69858. if (contours instanceof BABYLON.Path2) {
  69859. points = contours.getPoints();
  69860. }
  69861. else {
  69862. points = contours;
  69863. }
  69864. this._addToepoint(points);
  69865. this._points.add(points);
  69866. this._outlinepoints.add(points);
  69867. }
  69868. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  69869. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  69870. var p = points_1[_i];
  69871. this._epoints.push(p.x, p.y);
  69872. }
  69873. };
  69874. PolygonMeshBuilder.prototype.addHole = function (hole) {
  69875. this._points.add(hole);
  69876. var holepoints = new PolygonPoints();
  69877. holepoints.add(hole);
  69878. this._holes.push(holepoints);
  69879. this._eholes.push(this._epoints.length / 2);
  69880. this._addToepoint(hole);
  69881. return this;
  69882. };
  69883. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  69884. var _this = this;
  69885. if (updatable === void 0) { updatable = false; }
  69886. if (depth === void 0) { depth = 0; }
  69887. var result = new BABYLON.Mesh(this._name, this._scene);
  69888. var normals = new Array();
  69889. var positions = new Array();
  69890. var uvs = new Array();
  69891. var bounds = this._points.computeBounds();
  69892. this._points.elements.forEach(function (p) {
  69893. normals.push(0, 1.0, 0);
  69894. positions.push(p.x, 0, p.y);
  69895. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  69896. });
  69897. var indices = new Array();
  69898. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  69899. for (var i = 0; i < res.length; i++) {
  69900. indices.push(res[i]);
  69901. }
  69902. if (depth > 0) {
  69903. var positionscount = (positions.length / 3); //get the current pointcount
  69904. this._points.elements.forEach(function (p) {
  69905. normals.push(0, -1.0, 0);
  69906. positions.push(p.x, -depth, p.y);
  69907. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  69908. });
  69909. var totalCount = indices.length;
  69910. for (var i = 0; i < totalCount; i += 3) {
  69911. var i0 = indices[i + 0];
  69912. var i1 = indices[i + 1];
  69913. var i2 = indices[i + 2];
  69914. indices.push(i2 + positionscount);
  69915. indices.push(i1 + positionscount);
  69916. indices.push(i0 + positionscount);
  69917. }
  69918. //Add the sides
  69919. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  69920. this._holes.forEach(function (hole) {
  69921. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  69922. });
  69923. }
  69924. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  69925. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  69926. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  69927. result.setIndices(indices);
  69928. return result;
  69929. };
  69930. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  69931. var StartIndex = positions.length / 3;
  69932. var ulength = 0;
  69933. for (var i = 0; i < points.elements.length; i++) {
  69934. var p = points.elements[i];
  69935. var p1;
  69936. if ((i + 1) > points.elements.length - 1) {
  69937. p1 = points.elements[0];
  69938. }
  69939. else {
  69940. p1 = points.elements[i + 1];
  69941. }
  69942. positions.push(p.x, 0, p.y);
  69943. positions.push(p.x, -depth, p.y);
  69944. positions.push(p1.x, 0, p1.y);
  69945. positions.push(p1.x, -depth, p1.y);
  69946. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  69947. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  69948. var v3 = v2.subtract(v1);
  69949. var v4 = new BABYLON.Vector3(0, 1, 0);
  69950. var vn = BABYLON.Vector3.Cross(v3, v4);
  69951. vn = vn.normalize();
  69952. uvs.push(ulength / bounds.width, 0);
  69953. uvs.push(ulength / bounds.width, 1);
  69954. ulength += v3.length();
  69955. uvs.push((ulength / bounds.width), 0);
  69956. uvs.push((ulength / bounds.width), 1);
  69957. if (!flip) {
  69958. normals.push(-vn.x, -vn.y, -vn.z);
  69959. normals.push(-vn.x, -vn.y, -vn.z);
  69960. normals.push(-vn.x, -vn.y, -vn.z);
  69961. normals.push(-vn.x, -vn.y, -vn.z);
  69962. indices.push(StartIndex);
  69963. indices.push(StartIndex + 1);
  69964. indices.push(StartIndex + 2);
  69965. indices.push(StartIndex + 1);
  69966. indices.push(StartIndex + 3);
  69967. indices.push(StartIndex + 2);
  69968. }
  69969. else {
  69970. normals.push(vn.x, vn.y, vn.z);
  69971. normals.push(vn.x, vn.y, vn.z);
  69972. normals.push(vn.x, vn.y, vn.z);
  69973. normals.push(vn.x, vn.y, vn.z);
  69974. indices.push(StartIndex);
  69975. indices.push(StartIndex + 2);
  69976. indices.push(StartIndex + 1);
  69977. indices.push(StartIndex + 1);
  69978. indices.push(StartIndex + 2);
  69979. indices.push(StartIndex + 3);
  69980. }
  69981. StartIndex += 4;
  69982. }
  69983. ;
  69984. };
  69985. return PolygonMeshBuilder;
  69986. }());
  69987. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  69988. })(BABYLON || (BABYLON = {}));
  69989. //# sourceMappingURL=babylon.polygonMesh.js.map
  69990. var BABYLON;
  69991. (function (BABYLON) {
  69992. // Unique ID when we import meshes from Babylon to CSG
  69993. var currentCSGMeshId = 0;
  69994. // # class Vertex
  69995. // Represents a vertex of a polygon. Use your own vertex class instead of this
  69996. // one to provide additional features like texture coordinates and vertex
  69997. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  69998. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  69999. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  70000. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  70001. // is not used anywhere else.
  70002. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  70003. var Vertex = /** @class */ (function () {
  70004. function Vertex(pos, normal, uv) {
  70005. this.pos = pos;
  70006. this.normal = normal;
  70007. this.uv = uv;
  70008. }
  70009. Vertex.prototype.clone = function () {
  70010. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  70011. };
  70012. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  70013. // orientation of a polygon is flipped.
  70014. Vertex.prototype.flip = function () {
  70015. this.normal = this.normal.scale(-1);
  70016. };
  70017. // Create a new vertex between this vertex and `other` by linearly
  70018. // interpolating all properties using a parameter of `t`. Subclasses should
  70019. // override this to interpolate additional properties.
  70020. Vertex.prototype.interpolate = function (other, t) {
  70021. 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));
  70022. };
  70023. return Vertex;
  70024. }());
  70025. // # class Plane
  70026. // Represents a plane in 3D space.
  70027. var Plane = /** @class */ (function () {
  70028. function Plane(normal, w) {
  70029. this.normal = normal;
  70030. this.w = w;
  70031. }
  70032. Plane.FromPoints = function (a, b, c) {
  70033. var v0 = c.subtract(a);
  70034. var v1 = b.subtract(a);
  70035. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  70036. return null;
  70037. }
  70038. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  70039. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  70040. };
  70041. Plane.prototype.clone = function () {
  70042. return new Plane(this.normal.clone(), this.w);
  70043. };
  70044. Plane.prototype.flip = function () {
  70045. this.normal.scaleInPlace(-1);
  70046. this.w = -this.w;
  70047. };
  70048. // Split `polygon` by this plane if needed, then put the polygon or polygon
  70049. // fragments in the appropriate lists. Coplanar polygons go into either
  70050. // `coplanarFront` or `coplanarBack` depending on their orientation with
  70051. // respect to this plane. Polygons in front or in back of this plane go into
  70052. // either `front` or `back`.
  70053. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  70054. var COPLANAR = 0;
  70055. var FRONT = 1;
  70056. var BACK = 2;
  70057. var SPANNING = 3;
  70058. // Classify each point as well as the entire polygon into one of the above
  70059. // four classes.
  70060. var polygonType = 0;
  70061. var types = [];
  70062. var i;
  70063. var t;
  70064. for (i = 0; i < polygon.vertices.length; i++) {
  70065. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  70066. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  70067. polygonType |= type;
  70068. types.push(type);
  70069. }
  70070. // Put the polygon in the correct list, splitting it when necessary.
  70071. switch (polygonType) {
  70072. case COPLANAR:
  70073. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  70074. break;
  70075. case FRONT:
  70076. front.push(polygon);
  70077. break;
  70078. case BACK:
  70079. back.push(polygon);
  70080. break;
  70081. case SPANNING:
  70082. var f = [], b = [];
  70083. for (i = 0; i < polygon.vertices.length; i++) {
  70084. var j = (i + 1) % polygon.vertices.length;
  70085. var ti = types[i], tj = types[j];
  70086. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  70087. if (ti !== BACK)
  70088. f.push(vi);
  70089. if (ti !== FRONT)
  70090. b.push(ti !== BACK ? vi.clone() : vi);
  70091. if ((ti | tj) === SPANNING) {
  70092. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  70093. var v = vi.interpolate(vj, t);
  70094. f.push(v);
  70095. b.push(v.clone());
  70096. }
  70097. }
  70098. var poly;
  70099. if (f.length >= 3) {
  70100. poly = new Polygon(f, polygon.shared);
  70101. if (poly.plane)
  70102. front.push(poly);
  70103. }
  70104. if (b.length >= 3) {
  70105. poly = new Polygon(b, polygon.shared);
  70106. if (poly.plane)
  70107. back.push(poly);
  70108. }
  70109. break;
  70110. }
  70111. };
  70112. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  70113. // point is on the plane.
  70114. Plane.EPSILON = 1e-5;
  70115. return Plane;
  70116. }());
  70117. // # class Polygon
  70118. // Represents a convex polygon. The vertices used to initialize a polygon must
  70119. // be coplanar and form a convex loop.
  70120. //
  70121. // Each convex polygon has a `shared` property, which is shared between all
  70122. // polygons that are clones of each other or were split from the same polygon.
  70123. // This can be used to define per-polygon properties (such as surface color).
  70124. var Polygon = /** @class */ (function () {
  70125. function Polygon(vertices, shared) {
  70126. this.vertices = vertices;
  70127. this.shared = shared;
  70128. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  70129. }
  70130. Polygon.prototype.clone = function () {
  70131. var vertices = this.vertices.map(function (v) { return v.clone(); });
  70132. return new Polygon(vertices, this.shared);
  70133. };
  70134. Polygon.prototype.flip = function () {
  70135. this.vertices.reverse().map(function (v) { v.flip(); });
  70136. this.plane.flip();
  70137. };
  70138. return Polygon;
  70139. }());
  70140. // # class Node
  70141. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  70142. // by picking a polygon to split along. That polygon (and all other coplanar
  70143. // polygons) are added directly to that node and the other polygons are added to
  70144. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  70145. // no distinction between internal and leaf nodes.
  70146. var Node = /** @class */ (function () {
  70147. function Node(polygons) {
  70148. this.plane = null;
  70149. this.front = null;
  70150. this.back = null;
  70151. this.polygons = new Array();
  70152. if (polygons) {
  70153. this.build(polygons);
  70154. }
  70155. }
  70156. Node.prototype.clone = function () {
  70157. var node = new Node();
  70158. node.plane = this.plane && this.plane.clone();
  70159. node.front = this.front && this.front.clone();
  70160. node.back = this.back && this.back.clone();
  70161. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  70162. return node;
  70163. };
  70164. // Convert solid space to empty space and empty space to solid space.
  70165. Node.prototype.invert = function () {
  70166. for (var i = 0; i < this.polygons.length; i++) {
  70167. this.polygons[i].flip();
  70168. }
  70169. if (this.plane) {
  70170. this.plane.flip();
  70171. }
  70172. if (this.front) {
  70173. this.front.invert();
  70174. }
  70175. if (this.back) {
  70176. this.back.invert();
  70177. }
  70178. var temp = this.front;
  70179. this.front = this.back;
  70180. this.back = temp;
  70181. };
  70182. // Recursively remove all polygons in `polygons` that are inside this BSP
  70183. // tree.
  70184. Node.prototype.clipPolygons = function (polygons) {
  70185. if (!this.plane)
  70186. return polygons.slice();
  70187. var front = new Array(), back = new Array();
  70188. for (var i = 0; i < polygons.length; i++) {
  70189. this.plane.splitPolygon(polygons[i], front, back, front, back);
  70190. }
  70191. if (this.front) {
  70192. front = this.front.clipPolygons(front);
  70193. }
  70194. if (this.back) {
  70195. back = this.back.clipPolygons(back);
  70196. }
  70197. else {
  70198. back = [];
  70199. }
  70200. return front.concat(back);
  70201. };
  70202. // Remove all polygons in this BSP tree that are inside the other BSP tree
  70203. // `bsp`.
  70204. Node.prototype.clipTo = function (bsp) {
  70205. this.polygons = bsp.clipPolygons(this.polygons);
  70206. if (this.front)
  70207. this.front.clipTo(bsp);
  70208. if (this.back)
  70209. this.back.clipTo(bsp);
  70210. };
  70211. // Return a list of all polygons in this BSP tree.
  70212. Node.prototype.allPolygons = function () {
  70213. var polygons = this.polygons.slice();
  70214. if (this.front)
  70215. polygons = polygons.concat(this.front.allPolygons());
  70216. if (this.back)
  70217. polygons = polygons.concat(this.back.allPolygons());
  70218. return polygons;
  70219. };
  70220. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  70221. // new polygons are filtered down to the bottom of the tree and become new
  70222. // nodes there. Each set of polygons is partitioned using the first polygon
  70223. // (no heuristic is used to pick a good split).
  70224. Node.prototype.build = function (polygons) {
  70225. if (!polygons.length)
  70226. return;
  70227. if (!this.plane)
  70228. this.plane = polygons[0].plane.clone();
  70229. var front = new Array(), back = new Array();
  70230. for (var i = 0; i < polygons.length; i++) {
  70231. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  70232. }
  70233. if (front.length) {
  70234. if (!this.front)
  70235. this.front = new Node();
  70236. this.front.build(front);
  70237. }
  70238. if (back.length) {
  70239. if (!this.back)
  70240. this.back = new Node();
  70241. this.back.build(back);
  70242. }
  70243. };
  70244. return Node;
  70245. }());
  70246. var CSG = /** @class */ (function () {
  70247. function CSG() {
  70248. this.polygons = new Array();
  70249. }
  70250. // Convert BABYLON.Mesh to BABYLON.CSG
  70251. CSG.FromMesh = function (mesh) {
  70252. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  70253. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  70254. if (mesh instanceof BABYLON.Mesh) {
  70255. mesh.computeWorldMatrix(true);
  70256. matrix = mesh.getWorldMatrix();
  70257. meshPosition = mesh.position.clone();
  70258. meshRotation = mesh.rotation.clone();
  70259. if (mesh.rotationQuaternion) {
  70260. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  70261. }
  70262. meshScaling = mesh.scaling.clone();
  70263. }
  70264. else {
  70265. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  70266. }
  70267. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70268. var subMeshes = mesh.subMeshes;
  70269. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  70270. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  70271. vertices = [];
  70272. for (var j = 0; j < 3; j++) {
  70273. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  70274. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  70275. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  70276. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  70277. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  70278. vertex = new Vertex(position, normal, uv);
  70279. vertices.push(vertex);
  70280. }
  70281. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  70282. // To handle the case of degenerated triangle
  70283. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  70284. if (polygon.plane)
  70285. polygons.push(polygon);
  70286. }
  70287. }
  70288. var csg = CSG.FromPolygons(polygons);
  70289. csg.matrix = matrix;
  70290. csg.position = meshPosition;
  70291. csg.rotation = meshRotation;
  70292. csg.scaling = meshScaling;
  70293. csg.rotationQuaternion = meshRotationQuaternion;
  70294. currentCSGMeshId++;
  70295. return csg;
  70296. };
  70297. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  70298. CSG.FromPolygons = function (polygons) {
  70299. var csg = new CSG();
  70300. csg.polygons = polygons;
  70301. return csg;
  70302. };
  70303. CSG.prototype.clone = function () {
  70304. var csg = new CSG();
  70305. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  70306. csg.copyTransformAttributes(this);
  70307. return csg;
  70308. };
  70309. CSG.prototype.union = function (csg) {
  70310. var a = new Node(this.clone().polygons);
  70311. var b = new Node(csg.clone().polygons);
  70312. a.clipTo(b);
  70313. b.clipTo(a);
  70314. b.invert();
  70315. b.clipTo(a);
  70316. b.invert();
  70317. a.build(b.allPolygons());
  70318. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70319. };
  70320. CSG.prototype.unionInPlace = function (csg) {
  70321. var a = new Node(this.polygons);
  70322. var b = new Node(csg.polygons);
  70323. a.clipTo(b);
  70324. b.clipTo(a);
  70325. b.invert();
  70326. b.clipTo(a);
  70327. b.invert();
  70328. a.build(b.allPolygons());
  70329. this.polygons = a.allPolygons();
  70330. };
  70331. CSG.prototype.subtract = function (csg) {
  70332. var a = new Node(this.clone().polygons);
  70333. var b = new Node(csg.clone().polygons);
  70334. a.invert();
  70335. a.clipTo(b);
  70336. b.clipTo(a);
  70337. b.invert();
  70338. b.clipTo(a);
  70339. b.invert();
  70340. a.build(b.allPolygons());
  70341. a.invert();
  70342. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70343. };
  70344. CSG.prototype.subtractInPlace = function (csg) {
  70345. var a = new Node(this.polygons);
  70346. var b = new Node(csg.polygons);
  70347. a.invert();
  70348. a.clipTo(b);
  70349. b.clipTo(a);
  70350. b.invert();
  70351. b.clipTo(a);
  70352. b.invert();
  70353. a.build(b.allPolygons());
  70354. a.invert();
  70355. this.polygons = a.allPolygons();
  70356. };
  70357. CSG.prototype.intersect = function (csg) {
  70358. var a = new Node(this.clone().polygons);
  70359. var b = new Node(csg.clone().polygons);
  70360. a.invert();
  70361. b.clipTo(a);
  70362. b.invert();
  70363. a.clipTo(b);
  70364. b.clipTo(a);
  70365. a.build(b.allPolygons());
  70366. a.invert();
  70367. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70368. };
  70369. CSG.prototype.intersectInPlace = function (csg) {
  70370. var a = new Node(this.polygons);
  70371. var b = new Node(csg.polygons);
  70372. a.invert();
  70373. b.clipTo(a);
  70374. b.invert();
  70375. a.clipTo(b);
  70376. b.clipTo(a);
  70377. a.build(b.allPolygons());
  70378. a.invert();
  70379. this.polygons = a.allPolygons();
  70380. };
  70381. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  70382. // not modified.
  70383. CSG.prototype.inverse = function () {
  70384. var csg = this.clone();
  70385. csg.inverseInPlace();
  70386. return csg;
  70387. };
  70388. CSG.prototype.inverseInPlace = function () {
  70389. this.polygons.map(function (p) { p.flip(); });
  70390. };
  70391. // This is used to keep meshes transformations so they can be restored
  70392. // when we build back a Babylon Mesh
  70393. // NB : All CSG operations are performed in world coordinates
  70394. CSG.prototype.copyTransformAttributes = function (csg) {
  70395. this.matrix = csg.matrix;
  70396. this.position = csg.position;
  70397. this.rotation = csg.rotation;
  70398. this.scaling = csg.scaling;
  70399. this.rotationQuaternion = csg.rotationQuaternion;
  70400. return this;
  70401. };
  70402. // Build Raw mesh from CSG
  70403. // Coordinates here are in world space
  70404. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  70405. var matrix = this.matrix.clone();
  70406. matrix.invert();
  70407. 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;
  70408. if (keepSubMeshes) {
  70409. // Sort Polygons, since subMeshes are indices range
  70410. polygons.sort(function (a, b) {
  70411. if (a.shared.meshId === b.shared.meshId) {
  70412. return a.shared.subMeshId - b.shared.subMeshId;
  70413. }
  70414. else {
  70415. return a.shared.meshId - b.shared.meshId;
  70416. }
  70417. });
  70418. }
  70419. for (var i = 0, il = polygons.length; i < il; i++) {
  70420. polygon = polygons[i];
  70421. // Building SubMeshes
  70422. if (!subMesh_dict[polygon.shared.meshId]) {
  70423. subMesh_dict[polygon.shared.meshId] = {};
  70424. }
  70425. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  70426. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  70427. indexStart: +Infinity,
  70428. indexEnd: -Infinity,
  70429. materialIndex: polygon.shared.materialIndex
  70430. };
  70431. }
  70432. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  70433. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  70434. polygonIndices[0] = 0;
  70435. polygonIndices[1] = j - 1;
  70436. polygonIndices[2] = j;
  70437. for (var k = 0; k < 3; k++) {
  70438. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  70439. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  70440. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  70441. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  70442. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  70443. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  70444. // Check if 2 points can be merged
  70445. if (!(typeof vertex_idx !== 'undefined' &&
  70446. normals[vertex_idx * 3] === localNormal.x &&
  70447. normals[vertex_idx * 3 + 1] === localNormal.y &&
  70448. normals[vertex_idx * 3 + 2] === localNormal.z &&
  70449. uvs[vertex_idx * 2] === uv.x &&
  70450. uvs[vertex_idx * 2 + 1] === uv.y)) {
  70451. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  70452. uvs.push(uv.x, uv.y);
  70453. normals.push(normal.x, normal.y, normal.z);
  70454. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  70455. }
  70456. indices.push(vertex_idx);
  70457. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  70458. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  70459. currentIndex++;
  70460. }
  70461. }
  70462. }
  70463. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  70464. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  70465. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  70466. mesh.setIndices(indices, null);
  70467. if (keepSubMeshes) {
  70468. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  70469. var materialIndexOffset = 0, materialMaxIndex;
  70470. mesh.subMeshes = new Array();
  70471. for (var m in subMesh_dict) {
  70472. materialMaxIndex = -1;
  70473. for (var sm in subMesh_dict[m]) {
  70474. subMesh_obj = subMesh_dict[m][sm];
  70475. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  70476. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  70477. }
  70478. materialIndexOffset += ++materialMaxIndex;
  70479. }
  70480. }
  70481. return mesh;
  70482. };
  70483. // Build Mesh from CSG taking material and transforms into account
  70484. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  70485. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  70486. mesh.material = material;
  70487. mesh.position.copyFrom(this.position);
  70488. mesh.rotation.copyFrom(this.rotation);
  70489. if (this.rotationQuaternion) {
  70490. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  70491. }
  70492. mesh.scaling.copyFrom(this.scaling);
  70493. mesh.computeWorldMatrix(true);
  70494. return mesh;
  70495. };
  70496. return CSG;
  70497. }());
  70498. BABYLON.CSG = CSG;
  70499. })(BABYLON || (BABYLON = {}));
  70500. //# sourceMappingURL=babylon.csg.js.map
  70501. var BABYLON;
  70502. (function (BABYLON) {
  70503. var LensFlare = /** @class */ (function () {
  70504. function LensFlare(size, position, color, imgUrl, system) {
  70505. this.size = size;
  70506. this.position = position;
  70507. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  70508. this.color = color || new BABYLON.Color3(1, 1, 1);
  70509. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  70510. this._system = system;
  70511. system.lensFlares.push(this);
  70512. }
  70513. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  70514. return new LensFlare(size, position, color, imgUrl, system);
  70515. };
  70516. LensFlare.prototype.dispose = function () {
  70517. if (this.texture) {
  70518. this.texture.dispose();
  70519. }
  70520. // Remove from scene
  70521. var index = this._system.lensFlares.indexOf(this);
  70522. this._system.lensFlares.splice(index, 1);
  70523. };
  70524. ;
  70525. return LensFlare;
  70526. }());
  70527. BABYLON.LensFlare = LensFlare;
  70528. })(BABYLON || (BABYLON = {}));
  70529. //# sourceMappingURL=babylon.lensFlare.js.map
  70530. var BABYLON;
  70531. (function (BABYLON) {
  70532. var LensFlareSystem = /** @class */ (function () {
  70533. function LensFlareSystem(name, emitter, scene) {
  70534. this.name = name;
  70535. this.lensFlares = new Array();
  70536. this.borderLimit = 300;
  70537. this.viewportBorder = 0;
  70538. this.layerMask = 0x0FFFFFFF;
  70539. this._vertexBuffers = {};
  70540. this._isEnabled = true;
  70541. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70542. this._emitter = emitter;
  70543. this.id = name;
  70544. scene.lensFlareSystems.push(this);
  70545. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  70546. var engine = scene.getEngine();
  70547. // VBO
  70548. var vertices = [];
  70549. vertices.push(1, 1);
  70550. vertices.push(-1, 1);
  70551. vertices.push(-1, -1);
  70552. vertices.push(1, -1);
  70553. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70554. // Indices
  70555. var indices = [];
  70556. indices.push(0);
  70557. indices.push(1);
  70558. indices.push(2);
  70559. indices.push(0);
  70560. indices.push(2);
  70561. indices.push(3);
  70562. this._indexBuffer = engine.createIndexBuffer(indices);
  70563. // Effects
  70564. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  70565. }
  70566. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  70567. get: function () {
  70568. return this._isEnabled;
  70569. },
  70570. set: function (value) {
  70571. this._isEnabled = value;
  70572. },
  70573. enumerable: true,
  70574. configurable: true
  70575. });
  70576. LensFlareSystem.prototype.getScene = function () {
  70577. return this._scene;
  70578. };
  70579. LensFlareSystem.prototype.getEmitter = function () {
  70580. return this._emitter;
  70581. };
  70582. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  70583. this._emitter = newEmitter;
  70584. };
  70585. LensFlareSystem.prototype.getEmitterPosition = function () {
  70586. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  70587. };
  70588. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  70589. var position = this.getEmitterPosition();
  70590. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  70591. this._positionX = position.x;
  70592. this._positionY = position.y;
  70593. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  70594. if (this.viewportBorder > 0) {
  70595. globalViewport.x -= this.viewportBorder;
  70596. globalViewport.y -= this.viewportBorder;
  70597. globalViewport.width += this.viewportBorder * 2;
  70598. globalViewport.height += this.viewportBorder * 2;
  70599. position.x += this.viewportBorder;
  70600. position.y += this.viewportBorder;
  70601. this._positionX += this.viewportBorder;
  70602. this._positionY += this.viewportBorder;
  70603. }
  70604. if (position.z > 0) {
  70605. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  70606. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  70607. return true;
  70608. }
  70609. return true;
  70610. }
  70611. return false;
  70612. };
  70613. LensFlareSystem.prototype._isVisible = function () {
  70614. if (!this._isEnabled || !this._scene.activeCamera) {
  70615. return false;
  70616. }
  70617. var emitterPosition = this.getEmitterPosition();
  70618. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  70619. var distance = direction.length();
  70620. direction.normalize();
  70621. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  70622. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  70623. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  70624. };
  70625. LensFlareSystem.prototype.render = function () {
  70626. if (!this._effect.isReady() || !this._scene.activeCamera)
  70627. return false;
  70628. var engine = this._scene.getEngine();
  70629. var viewport = this._scene.activeCamera.viewport;
  70630. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  70631. // Position
  70632. if (!this.computeEffectivePosition(globalViewport)) {
  70633. return false;
  70634. }
  70635. // Visibility
  70636. if (!this._isVisible()) {
  70637. return false;
  70638. }
  70639. // Intensity
  70640. var awayX;
  70641. var awayY;
  70642. if (this._positionX < this.borderLimit + globalViewport.x) {
  70643. awayX = this.borderLimit + globalViewport.x - this._positionX;
  70644. }
  70645. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  70646. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  70647. }
  70648. else {
  70649. awayX = 0;
  70650. }
  70651. if (this._positionY < this.borderLimit + globalViewport.y) {
  70652. awayY = this.borderLimit + globalViewport.y - this._positionY;
  70653. }
  70654. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  70655. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  70656. }
  70657. else {
  70658. awayY = 0;
  70659. }
  70660. var away = (awayX > awayY) ? awayX : awayY;
  70661. away -= this.viewportBorder;
  70662. if (away > this.borderLimit) {
  70663. away = this.borderLimit;
  70664. }
  70665. var intensity = 1.0 - (away / this.borderLimit);
  70666. if (intensity < 0) {
  70667. return false;
  70668. }
  70669. if (intensity > 1.0) {
  70670. intensity = 1.0;
  70671. }
  70672. if (this.viewportBorder > 0) {
  70673. globalViewport.x += this.viewportBorder;
  70674. globalViewport.y += this.viewportBorder;
  70675. globalViewport.width -= this.viewportBorder * 2;
  70676. globalViewport.height -= this.viewportBorder * 2;
  70677. this._positionX -= this.viewportBorder;
  70678. this._positionY -= this.viewportBorder;
  70679. }
  70680. // Position
  70681. var centerX = globalViewport.x + globalViewport.width / 2;
  70682. var centerY = globalViewport.y + globalViewport.height / 2;
  70683. var distX = centerX - this._positionX;
  70684. var distY = centerY - this._positionY;
  70685. // Effects
  70686. engine.enableEffect(this._effect);
  70687. engine.setState(false);
  70688. engine.setDepthBuffer(false);
  70689. // VBOs
  70690. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70691. // Flares
  70692. for (var index = 0; index < this.lensFlares.length; index++) {
  70693. var flare = this.lensFlares[index];
  70694. engine.setAlphaMode(flare.alphaMode);
  70695. var x = centerX - (distX * flare.position);
  70696. var y = centerY - (distY * flare.position);
  70697. var cw = flare.size;
  70698. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  70699. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  70700. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  70701. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  70702. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  70703. // Texture
  70704. this._effect.setTexture("textureSampler", flare.texture);
  70705. // Color
  70706. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  70707. // Draw order
  70708. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70709. }
  70710. engine.setDepthBuffer(true);
  70711. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70712. return true;
  70713. };
  70714. LensFlareSystem.prototype.dispose = function () {
  70715. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70716. if (vertexBuffer) {
  70717. vertexBuffer.dispose();
  70718. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70719. }
  70720. if (this._indexBuffer) {
  70721. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70722. this._indexBuffer = null;
  70723. }
  70724. while (this.lensFlares.length) {
  70725. this.lensFlares[0].dispose();
  70726. }
  70727. // Remove from scene
  70728. var index = this._scene.lensFlareSystems.indexOf(this);
  70729. this._scene.lensFlareSystems.splice(index, 1);
  70730. };
  70731. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  70732. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  70733. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  70734. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  70735. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  70736. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  70737. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  70738. var parsedFlare = parsedLensFlareSystem.flares[index];
  70739. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  70740. }
  70741. return lensFlareSystem;
  70742. };
  70743. LensFlareSystem.prototype.serialize = function () {
  70744. var serializationObject = {};
  70745. serializationObject.id = this.id;
  70746. serializationObject.name = this.name;
  70747. serializationObject.emitterId = this.getEmitter().id;
  70748. serializationObject.borderLimit = this.borderLimit;
  70749. serializationObject.flares = [];
  70750. for (var index = 0; index < this.lensFlares.length; index++) {
  70751. var flare = this.lensFlares[index];
  70752. serializationObject.flares.push({
  70753. size: flare.size,
  70754. position: flare.position,
  70755. color: flare.color.asArray(),
  70756. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  70757. });
  70758. }
  70759. return serializationObject;
  70760. };
  70761. return LensFlareSystem;
  70762. }());
  70763. BABYLON.LensFlareSystem = LensFlareSystem;
  70764. })(BABYLON || (BABYLON = {}));
  70765. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  70766. var BABYLON;
  70767. (function (BABYLON) {
  70768. /**
  70769. * This is a holder class for the physics joint created by the physics plugin.
  70770. * It holds a set of functions to control the underlying joint.
  70771. */
  70772. var PhysicsJoint = /** @class */ (function () {
  70773. function PhysicsJoint(type, jointData) {
  70774. this.type = type;
  70775. this.jointData = jointData;
  70776. jointData.nativeParams = jointData.nativeParams || {};
  70777. }
  70778. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  70779. get: function () {
  70780. return this._physicsJoint;
  70781. },
  70782. set: function (newJoint) {
  70783. if (this._physicsJoint) {
  70784. //remove from the wolrd
  70785. }
  70786. this._physicsJoint = newJoint;
  70787. },
  70788. enumerable: true,
  70789. configurable: true
  70790. });
  70791. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  70792. set: function (physicsPlugin) {
  70793. this._physicsPlugin = physicsPlugin;
  70794. },
  70795. enumerable: true,
  70796. configurable: true
  70797. });
  70798. /**
  70799. * Execute a function that is physics-plugin specific.
  70800. * @param {Function} func the function that will be executed.
  70801. * It accepts two parameters: the physics world and the physics joint.
  70802. */
  70803. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  70804. func(this._physicsPlugin.world, this._physicsJoint);
  70805. };
  70806. //TODO check if the native joints are the same
  70807. //Joint Types
  70808. PhysicsJoint.DistanceJoint = 0;
  70809. PhysicsJoint.HingeJoint = 1;
  70810. PhysicsJoint.BallAndSocketJoint = 2;
  70811. PhysicsJoint.WheelJoint = 3;
  70812. PhysicsJoint.SliderJoint = 4;
  70813. //OIMO
  70814. PhysicsJoint.PrismaticJoint = 5;
  70815. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  70816. PhysicsJoint.UniversalJoint = 6;
  70817. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  70818. //Cannon
  70819. //Similar to a Ball-Joint. Different in params
  70820. PhysicsJoint.PointToPointJoint = 8;
  70821. //Cannon only at the moment
  70822. PhysicsJoint.SpringJoint = 9;
  70823. PhysicsJoint.LockJoint = 10;
  70824. return PhysicsJoint;
  70825. }());
  70826. BABYLON.PhysicsJoint = PhysicsJoint;
  70827. /**
  70828. * A class representing a physics distance joint.
  70829. */
  70830. var DistanceJoint = /** @class */ (function (_super) {
  70831. __extends(DistanceJoint, _super);
  70832. function DistanceJoint(jointData) {
  70833. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  70834. }
  70835. /**
  70836. * Update the predefined distance.
  70837. */
  70838. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  70839. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  70840. };
  70841. return DistanceJoint;
  70842. }(PhysicsJoint));
  70843. BABYLON.DistanceJoint = DistanceJoint;
  70844. var MotorEnabledJoint = /** @class */ (function (_super) {
  70845. __extends(MotorEnabledJoint, _super);
  70846. function MotorEnabledJoint(type, jointData) {
  70847. return _super.call(this, type, jointData) || this;
  70848. }
  70849. /**
  70850. * Set the motor values.
  70851. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70852. * @param {number} force the force to apply
  70853. * @param {number} maxForce max force for this motor.
  70854. */
  70855. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  70856. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70857. };
  70858. /**
  70859. * Set the motor's limits.
  70860. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70861. */
  70862. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70863. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70864. };
  70865. return MotorEnabledJoint;
  70866. }(PhysicsJoint));
  70867. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  70868. /**
  70869. * This class represents a single hinge physics joint
  70870. */
  70871. var HingeJoint = /** @class */ (function (_super) {
  70872. __extends(HingeJoint, _super);
  70873. function HingeJoint(jointData) {
  70874. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  70875. }
  70876. /**
  70877. * Set the motor values.
  70878. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70879. * @param {number} force the force to apply
  70880. * @param {number} maxForce max force for this motor.
  70881. */
  70882. HingeJoint.prototype.setMotor = function (force, maxForce) {
  70883. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70884. };
  70885. /**
  70886. * Set the motor's limits.
  70887. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70888. */
  70889. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70890. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70891. };
  70892. return HingeJoint;
  70893. }(MotorEnabledJoint));
  70894. BABYLON.HingeJoint = HingeJoint;
  70895. /**
  70896. * This class represents a dual hinge physics joint (same as wheel joint)
  70897. */
  70898. var Hinge2Joint = /** @class */ (function (_super) {
  70899. __extends(Hinge2Joint, _super);
  70900. function Hinge2Joint(jointData) {
  70901. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  70902. }
  70903. /**
  70904. * Set the motor values.
  70905. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70906. * @param {number} force the force to apply
  70907. * @param {number} maxForce max force for this motor.
  70908. * @param {motorIndex} the motor's index, 0 or 1.
  70909. */
  70910. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  70911. if (motorIndex === void 0) { motorIndex = 0; }
  70912. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  70913. };
  70914. /**
  70915. * Set the motor limits.
  70916. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70917. * @param {number} upperLimit the upper limit
  70918. * @param {number} lowerLimit lower limit
  70919. * @param {motorIndex} the motor's index, 0 or 1.
  70920. */
  70921. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  70922. if (motorIndex === void 0) { motorIndex = 0; }
  70923. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  70924. };
  70925. return Hinge2Joint;
  70926. }(MotorEnabledJoint));
  70927. BABYLON.Hinge2Joint = Hinge2Joint;
  70928. })(BABYLON || (BABYLON = {}));
  70929. //# sourceMappingURL=babylon.physicsJoint.js.map
  70930. var BABYLON;
  70931. (function (BABYLON) {
  70932. var PhysicsImpostor = /** @class */ (function () {
  70933. function PhysicsImpostor(object, type, _options, _scene) {
  70934. if (_options === void 0) { _options = { mass: 0 }; }
  70935. var _this = this;
  70936. this.object = object;
  70937. this.type = type;
  70938. this._options = _options;
  70939. this._scene = _scene;
  70940. this._bodyUpdateRequired = false;
  70941. this._onBeforePhysicsStepCallbacks = new Array();
  70942. this._onAfterPhysicsStepCallbacks = new Array();
  70943. this._onPhysicsCollideCallbacks = [];
  70944. this._deltaPosition = BABYLON.Vector3.Zero();
  70945. this._isDisposed = false;
  70946. //temp variables for parent rotation calculations
  70947. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  70948. this._tmpQuat = new BABYLON.Quaternion();
  70949. this._tmpQuat2 = new BABYLON.Quaternion();
  70950. /**
  70951. * this function is executed by the physics engine.
  70952. */
  70953. this.beforeStep = function () {
  70954. if (!_this._physicsEngine) {
  70955. return;
  70956. }
  70957. _this.object.translate(_this._deltaPosition, -1);
  70958. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  70959. _this.object.computeWorldMatrix(false);
  70960. if (_this.object.parent && _this.object.rotationQuaternion) {
  70961. _this.getParentsRotation();
  70962. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  70963. }
  70964. else {
  70965. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  70966. }
  70967. if (!_this._options.disableBidirectionalTransformation) {
  70968. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  70969. }
  70970. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  70971. func(_this);
  70972. });
  70973. };
  70974. /**
  70975. * this function is executed by the physics engine.
  70976. */
  70977. this.afterStep = function () {
  70978. if (!_this._physicsEngine) {
  70979. return;
  70980. }
  70981. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  70982. func(_this);
  70983. });
  70984. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  70985. // object has now its world rotation. needs to be converted to local.
  70986. if (_this.object.parent && _this.object.rotationQuaternion) {
  70987. _this.getParentsRotation();
  70988. _this._tmpQuat.conjugateInPlace();
  70989. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  70990. }
  70991. // take the position set and make it the absolute position of this object.
  70992. _this.object.setAbsolutePosition(_this.object.position);
  70993. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  70994. _this.object.translate(_this._deltaPosition, 1);
  70995. };
  70996. /**
  70997. * Legacy collision detection event support
  70998. */
  70999. this.onCollideEvent = null;
  71000. //event and body object due to cannon's event-based architecture.
  71001. this.onCollide = function (e) {
  71002. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  71003. return;
  71004. }
  71005. if (!_this._physicsEngine) {
  71006. return;
  71007. }
  71008. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  71009. if (otherImpostor) {
  71010. // Legacy collision detection event support
  71011. if (_this.onCollideEvent) {
  71012. _this.onCollideEvent(_this, otherImpostor);
  71013. }
  71014. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  71015. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  71016. }).forEach(function (obj) {
  71017. obj.callback(_this, otherImpostor);
  71018. });
  71019. }
  71020. };
  71021. //sanity check!
  71022. if (!this.object) {
  71023. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  71024. return;
  71025. }
  71026. //legacy support for old syntax.
  71027. if (!this._scene && object.getScene) {
  71028. this._scene = object.getScene();
  71029. }
  71030. if (!this._scene) {
  71031. return;
  71032. }
  71033. this._physicsEngine = this._scene.getPhysicsEngine();
  71034. if (!this._physicsEngine) {
  71035. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  71036. }
  71037. else {
  71038. //set the object's quaternion, if not set
  71039. if (!this.object.rotationQuaternion) {
  71040. if (this.object.rotation) {
  71041. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  71042. }
  71043. else {
  71044. this.object.rotationQuaternion = new BABYLON.Quaternion();
  71045. }
  71046. }
  71047. //default options params
  71048. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  71049. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  71050. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  71051. this._joints = [];
  71052. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  71053. if (!this.object.parent || this._options.ignoreParent) {
  71054. this._init();
  71055. }
  71056. else if (this.object.parent.physicsImpostor) {
  71057. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  71058. }
  71059. }
  71060. }
  71061. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  71062. get: function () {
  71063. return this._isDisposed;
  71064. },
  71065. enumerable: true,
  71066. configurable: true
  71067. });
  71068. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  71069. get: function () {
  71070. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  71071. },
  71072. set: function (value) {
  71073. this.setMass(value);
  71074. },
  71075. enumerable: true,
  71076. configurable: true
  71077. });
  71078. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  71079. get: function () {
  71080. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  71081. },
  71082. set: function (value) {
  71083. if (!this._physicsEngine) {
  71084. return;
  71085. }
  71086. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  71087. },
  71088. enumerable: true,
  71089. configurable: true
  71090. });
  71091. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  71092. get: function () {
  71093. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  71094. },
  71095. set: function (value) {
  71096. if (!this._physicsEngine) {
  71097. return;
  71098. }
  71099. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  71100. },
  71101. enumerable: true,
  71102. configurable: true
  71103. });
  71104. /**
  71105. * This function will completly initialize this impostor.
  71106. * It will create a new body - but only if this mesh has no parent.
  71107. * If it has, this impostor will not be used other than to define the impostor
  71108. * of the child mesh.
  71109. */
  71110. PhysicsImpostor.prototype._init = function () {
  71111. if (!this._physicsEngine) {
  71112. return;
  71113. }
  71114. this._physicsEngine.removeImpostor(this);
  71115. this.physicsBody = null;
  71116. this._parent = this._parent || this._getPhysicsParent();
  71117. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  71118. this._physicsEngine.addImpostor(this);
  71119. }
  71120. };
  71121. PhysicsImpostor.prototype._getPhysicsParent = function () {
  71122. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  71123. var parentMesh = this.object.parent;
  71124. return parentMesh.physicsImpostor;
  71125. }
  71126. return null;
  71127. };
  71128. /**
  71129. * Should a new body be generated.
  71130. */
  71131. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  71132. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  71133. };
  71134. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  71135. this.forceUpdate();
  71136. };
  71137. /**
  71138. * Force a regeneration of this or the parent's impostor's body.
  71139. * Use under cautious - This will remove all joints already implemented.
  71140. */
  71141. PhysicsImpostor.prototype.forceUpdate = function () {
  71142. this._init();
  71143. if (this.parent && !this._options.ignoreParent) {
  71144. this.parent.forceUpdate();
  71145. }
  71146. };
  71147. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  71148. /*public get mesh(): AbstractMesh {
  71149. return this._mesh;
  71150. }*/
  71151. /**
  71152. * Gets the body that holds this impostor. Either its own, or its parent.
  71153. */
  71154. get: function () {
  71155. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  71156. },
  71157. /**
  71158. * Set the physics body. Used mainly by the physics engine/plugin
  71159. */
  71160. set: function (physicsBody) {
  71161. if (this._physicsBody && this._physicsEngine) {
  71162. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  71163. }
  71164. this._physicsBody = physicsBody;
  71165. this.resetUpdateFlags();
  71166. },
  71167. enumerable: true,
  71168. configurable: true
  71169. });
  71170. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  71171. get: function () {
  71172. return !this._options.ignoreParent && this._parent ? this._parent : null;
  71173. },
  71174. set: function (value) {
  71175. this._parent = value;
  71176. },
  71177. enumerable: true,
  71178. configurable: true
  71179. });
  71180. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  71181. this._bodyUpdateRequired = false;
  71182. };
  71183. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  71184. if (this.object.getBoundingInfo) {
  71185. var q = this.object.rotationQuaternion;
  71186. //reset rotation
  71187. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  71188. //calculate the world matrix with no rotation
  71189. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71190. var boundingInfo = this.object.getBoundingInfo();
  71191. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  71192. //bring back the rotation
  71193. this.object.rotationQuaternion = q;
  71194. //calculate the world matrix with the new rotation
  71195. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71196. return size;
  71197. }
  71198. else {
  71199. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  71200. }
  71201. };
  71202. PhysicsImpostor.prototype.getObjectCenter = function () {
  71203. if (this.object.getBoundingInfo) {
  71204. var boundingInfo = this.object.getBoundingInfo();
  71205. return boundingInfo.boundingBox.centerWorld;
  71206. }
  71207. else {
  71208. return this.object.position;
  71209. }
  71210. };
  71211. /**
  71212. * Get a specific parametes from the options parameter.
  71213. */
  71214. PhysicsImpostor.prototype.getParam = function (paramName) {
  71215. return this._options[paramName];
  71216. };
  71217. /**
  71218. * Sets a specific parameter in the options given to the physics plugin
  71219. */
  71220. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  71221. this._options[paramName] = value;
  71222. this._bodyUpdateRequired = true;
  71223. };
  71224. /**
  71225. * Specifically change the body's mass option. Won't recreate the physics body object
  71226. */
  71227. PhysicsImpostor.prototype.setMass = function (mass) {
  71228. if (this.getParam("mass") !== mass) {
  71229. this.setParam("mass", mass);
  71230. }
  71231. if (this._physicsEngine) {
  71232. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  71233. }
  71234. };
  71235. PhysicsImpostor.prototype.getLinearVelocity = function () {
  71236. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  71237. };
  71238. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  71239. if (this._physicsEngine) {
  71240. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  71241. }
  71242. };
  71243. PhysicsImpostor.prototype.getAngularVelocity = function () {
  71244. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  71245. };
  71246. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  71247. if (this._physicsEngine) {
  71248. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  71249. }
  71250. };
  71251. /**
  71252. * Execute a function with the physics plugin native code.
  71253. * Provide a function the will have two variables - the world object and the physics body object.
  71254. */
  71255. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  71256. if (this._physicsEngine) {
  71257. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  71258. }
  71259. };
  71260. /**
  71261. * Register a function that will be executed before the physics world is stepping forward.
  71262. */
  71263. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  71264. this._onBeforePhysicsStepCallbacks.push(func);
  71265. };
  71266. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  71267. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  71268. if (index > -1) {
  71269. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  71270. }
  71271. else {
  71272. BABYLON.Tools.Warn("Function to remove was not found");
  71273. }
  71274. };
  71275. /**
  71276. * Register a function that will be executed after the physics step
  71277. */
  71278. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  71279. this._onAfterPhysicsStepCallbacks.push(func);
  71280. };
  71281. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  71282. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  71283. if (index > -1) {
  71284. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  71285. }
  71286. else {
  71287. BABYLON.Tools.Warn("Function to remove was not found");
  71288. }
  71289. };
  71290. /**
  71291. * register a function that will be executed when this impostor collides against a different body.
  71292. */
  71293. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  71294. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71295. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  71296. };
  71297. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  71298. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71299. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  71300. if (index > -1) {
  71301. this._onPhysicsCollideCallbacks.splice(index, 1);
  71302. }
  71303. else {
  71304. BABYLON.Tools.Warn("Function to remove was not found");
  71305. }
  71306. };
  71307. PhysicsImpostor.prototype.getParentsRotation = function () {
  71308. var parent = this.object.parent;
  71309. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  71310. while (parent) {
  71311. if (parent.rotationQuaternion) {
  71312. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  71313. }
  71314. else {
  71315. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  71316. }
  71317. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  71318. parent = parent.parent;
  71319. }
  71320. return this._tmpQuat;
  71321. };
  71322. /**
  71323. * Apply a force
  71324. */
  71325. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  71326. if (this._physicsEngine) {
  71327. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  71328. }
  71329. return this;
  71330. };
  71331. /**
  71332. * Apply an impulse
  71333. */
  71334. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  71335. if (this._physicsEngine) {
  71336. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  71337. }
  71338. return this;
  71339. };
  71340. /**
  71341. * A help function to create a joint.
  71342. */
  71343. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  71344. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  71345. this.addJoint(otherImpostor, joint);
  71346. return this;
  71347. };
  71348. /**
  71349. * Add a joint to this impostor with a different impostor.
  71350. */
  71351. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  71352. this._joints.push({
  71353. otherImpostor: otherImpostor,
  71354. joint: joint
  71355. });
  71356. if (this._physicsEngine) {
  71357. this._physicsEngine.addJoint(this, otherImpostor, joint);
  71358. }
  71359. return this;
  71360. };
  71361. /**
  71362. * Will keep this body still, in a sleep mode.
  71363. */
  71364. PhysicsImpostor.prototype.sleep = function () {
  71365. if (this._physicsEngine) {
  71366. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  71367. }
  71368. return this;
  71369. };
  71370. /**
  71371. * Wake the body up.
  71372. */
  71373. PhysicsImpostor.prototype.wakeUp = function () {
  71374. if (this._physicsEngine) {
  71375. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  71376. }
  71377. return this;
  71378. };
  71379. PhysicsImpostor.prototype.clone = function (newObject) {
  71380. if (!newObject)
  71381. return null;
  71382. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  71383. };
  71384. PhysicsImpostor.prototype.dispose = function () {
  71385. var _this = this;
  71386. //no dispose if no physics engine is available.
  71387. if (!this._physicsEngine) {
  71388. return;
  71389. }
  71390. this._joints.forEach(function (j) {
  71391. if (_this._physicsEngine) {
  71392. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  71393. }
  71394. });
  71395. //dispose the physics body
  71396. this._physicsEngine.removeImpostor(this);
  71397. if (this.parent) {
  71398. this.parent.forceUpdate();
  71399. }
  71400. else {
  71401. /*this._object.getChildMeshes().forEach(function(mesh) {
  71402. if (mesh.physicsImpostor) {
  71403. if (disposeChildren) {
  71404. mesh.physicsImpostor.dispose();
  71405. mesh.physicsImpostor = null;
  71406. }
  71407. }
  71408. })*/
  71409. }
  71410. this._isDisposed = true;
  71411. };
  71412. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  71413. this._deltaPosition.copyFrom(position);
  71414. };
  71415. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  71416. if (!this._deltaRotation) {
  71417. this._deltaRotation = new BABYLON.Quaternion();
  71418. }
  71419. this._deltaRotation.copyFrom(rotation);
  71420. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  71421. };
  71422. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  71423. if (this._physicsEngine) {
  71424. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  71425. }
  71426. return this;
  71427. };
  71428. PhysicsImpostor.prototype.getRadius = function () {
  71429. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  71430. };
  71431. /**
  71432. * Sync a bone with this impostor
  71433. * @param bone The bone to sync to the impostor.
  71434. * @param boneMesh The mesh that the bone is influencing.
  71435. * @param jointPivot The pivot of the joint / bone in local space.
  71436. * @param distToJoint Optional distance from the impostor to the joint.
  71437. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71438. */
  71439. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  71440. var tempVec = PhysicsImpostor._tmpVecs[0];
  71441. var mesh = this.object;
  71442. if (mesh.rotationQuaternion) {
  71443. if (adjustRotation) {
  71444. var tempQuat = PhysicsImpostor._tmpQuat;
  71445. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  71446. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  71447. }
  71448. else {
  71449. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  71450. }
  71451. }
  71452. tempVec.x = 0;
  71453. tempVec.y = 0;
  71454. tempVec.z = 0;
  71455. if (jointPivot) {
  71456. tempVec.x = jointPivot.x;
  71457. tempVec.y = jointPivot.y;
  71458. tempVec.z = jointPivot.z;
  71459. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  71460. if (distToJoint === undefined || distToJoint === null) {
  71461. distToJoint = jointPivot.length();
  71462. }
  71463. tempVec.x *= distToJoint;
  71464. tempVec.y *= distToJoint;
  71465. tempVec.z *= distToJoint;
  71466. }
  71467. if (bone.getParent()) {
  71468. tempVec.addInPlace(mesh.getAbsolutePosition());
  71469. bone.setAbsolutePosition(tempVec, boneMesh);
  71470. }
  71471. else {
  71472. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  71473. boneMesh.position.x -= tempVec.x;
  71474. boneMesh.position.y -= tempVec.y;
  71475. boneMesh.position.z -= tempVec.z;
  71476. }
  71477. };
  71478. /**
  71479. * Sync impostor to a bone
  71480. * @param bone The bone that the impostor will be synced to.
  71481. * @param boneMesh The mesh that the bone is influencing.
  71482. * @param jointPivot The pivot of the joint / bone in local space.
  71483. * @param distToJoint Optional distance from the impostor to the joint.
  71484. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71485. * @param boneAxis Optional vector3 axis the bone is aligned with
  71486. */
  71487. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  71488. var mesh = this.object;
  71489. if (mesh.rotationQuaternion) {
  71490. if (adjustRotation) {
  71491. var tempQuat = PhysicsImpostor._tmpQuat;
  71492. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  71493. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  71494. }
  71495. else {
  71496. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  71497. }
  71498. }
  71499. var pos = PhysicsImpostor._tmpVecs[0];
  71500. var boneDir = PhysicsImpostor._tmpVecs[1];
  71501. if (!boneAxis) {
  71502. boneAxis = PhysicsImpostor._tmpVecs[2];
  71503. boneAxis.x = 0;
  71504. boneAxis.y = 1;
  71505. boneAxis.z = 0;
  71506. }
  71507. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  71508. bone.getAbsolutePositionToRef(boneMesh, pos);
  71509. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  71510. distToJoint = jointPivot.length();
  71511. }
  71512. if (distToJoint !== undefined && distToJoint !== null) {
  71513. pos.x += boneDir.x * distToJoint;
  71514. pos.y += boneDir.y * distToJoint;
  71515. pos.z += boneDir.z * distToJoint;
  71516. }
  71517. mesh.setAbsolutePosition(pos);
  71518. };
  71519. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  71520. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  71521. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71522. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  71523. //Impostor types
  71524. PhysicsImpostor.NoImpostor = 0;
  71525. PhysicsImpostor.SphereImpostor = 1;
  71526. PhysicsImpostor.BoxImpostor = 2;
  71527. PhysicsImpostor.PlaneImpostor = 3;
  71528. PhysicsImpostor.MeshImpostor = 4;
  71529. PhysicsImpostor.CylinderImpostor = 7;
  71530. PhysicsImpostor.ParticleImpostor = 8;
  71531. PhysicsImpostor.HeightmapImpostor = 9;
  71532. return PhysicsImpostor;
  71533. }());
  71534. BABYLON.PhysicsImpostor = PhysicsImpostor;
  71535. })(BABYLON || (BABYLON = {}));
  71536. //# sourceMappingURL=babylon.physicsImpostor.js.map
  71537. var BABYLON;
  71538. (function (BABYLON) {
  71539. var PhysicsEngine = /** @class */ (function () {
  71540. function PhysicsEngine(gravity, _physicsPlugin) {
  71541. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  71542. this._physicsPlugin = _physicsPlugin;
  71543. //new methods and parameters
  71544. this._impostors = [];
  71545. this._joints = [];
  71546. if (!this._physicsPlugin.isSupported()) {
  71547. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  71548. + "Please make sure it is included.");
  71549. }
  71550. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  71551. this.setGravity(gravity);
  71552. this.setTimeStep();
  71553. }
  71554. PhysicsEngine.prototype.setGravity = function (gravity) {
  71555. this.gravity = gravity;
  71556. this._physicsPlugin.setGravity(this.gravity);
  71557. };
  71558. /**
  71559. * Set the time step of the physics engine.
  71560. * default is 1/60.
  71561. * To slow it down, enter 1/600 for example.
  71562. * To speed it up, 1/30
  71563. * @param {number} newTimeStep the new timestep to apply to this world.
  71564. */
  71565. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  71566. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  71567. this._physicsPlugin.setTimeStep(newTimeStep);
  71568. };
  71569. /**
  71570. * Get the time step of the physics engine.
  71571. */
  71572. PhysicsEngine.prototype.getTimeStep = function () {
  71573. return this._physicsPlugin.getTimeStep();
  71574. };
  71575. PhysicsEngine.prototype.dispose = function () {
  71576. this._impostors.forEach(function (impostor) {
  71577. impostor.dispose();
  71578. });
  71579. this._physicsPlugin.dispose();
  71580. };
  71581. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  71582. return this._physicsPlugin.name;
  71583. };
  71584. /**
  71585. * Adding a new impostor for the impostor tracking.
  71586. * This will be done by the impostor itself.
  71587. * @param {PhysicsImpostor} impostor the impostor to add
  71588. */
  71589. PhysicsEngine.prototype.addImpostor = function (impostor) {
  71590. impostor.uniqueId = this._impostors.push(impostor);
  71591. //if no parent, generate the body
  71592. if (!impostor.parent) {
  71593. this._physicsPlugin.generatePhysicsBody(impostor);
  71594. }
  71595. };
  71596. /**
  71597. * Remove an impostor from the engine.
  71598. * This impostor and its mesh will not longer be updated by the physics engine.
  71599. * @param {PhysicsImpostor} impostor the impostor to remove
  71600. */
  71601. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  71602. var index = this._impostors.indexOf(impostor);
  71603. if (index > -1) {
  71604. var removed = this._impostors.splice(index, 1);
  71605. //Is it needed?
  71606. if (removed.length) {
  71607. //this will also remove it from the world.
  71608. removed[0].physicsBody = null;
  71609. }
  71610. }
  71611. };
  71612. /**
  71613. * Add a joint to the physics engine
  71614. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  71615. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  71616. * @param {PhysicsJoint} the joint that will connect both impostors.
  71617. */
  71618. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  71619. var impostorJoint = {
  71620. mainImpostor: mainImpostor,
  71621. connectedImpostor: connectedImpostor,
  71622. joint: joint
  71623. };
  71624. joint.physicsPlugin = this._physicsPlugin;
  71625. this._joints.push(impostorJoint);
  71626. this._physicsPlugin.generateJoint(impostorJoint);
  71627. };
  71628. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  71629. var matchingJoints = this._joints.filter(function (impostorJoint) {
  71630. return (impostorJoint.connectedImpostor === connectedImpostor
  71631. && impostorJoint.joint === joint
  71632. && impostorJoint.mainImpostor === mainImpostor);
  71633. });
  71634. if (matchingJoints.length) {
  71635. this._physicsPlugin.removeJoint(matchingJoints[0]);
  71636. //TODO remove it from the list as well
  71637. }
  71638. };
  71639. /**
  71640. * Called by the scene. no need to call it.
  71641. */
  71642. PhysicsEngine.prototype._step = function (delta) {
  71643. var _this = this;
  71644. //check if any mesh has no body / requires an update
  71645. this._impostors.forEach(function (impostor) {
  71646. if (impostor.isBodyInitRequired()) {
  71647. _this._physicsPlugin.generatePhysicsBody(impostor);
  71648. }
  71649. });
  71650. if (delta > 0.1) {
  71651. delta = 0.1;
  71652. }
  71653. else if (delta <= 0) {
  71654. delta = 1.0 / 60.0;
  71655. }
  71656. this._physicsPlugin.executeStep(delta, this._impostors);
  71657. };
  71658. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  71659. return this._physicsPlugin;
  71660. };
  71661. PhysicsEngine.prototype.getImpostors = function () {
  71662. return this._impostors;
  71663. };
  71664. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  71665. for (var i = 0; i < this._impostors.length; ++i) {
  71666. if (this._impostors[i].object === object) {
  71667. return this._impostors[i];
  71668. }
  71669. }
  71670. return null;
  71671. };
  71672. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  71673. for (var i = 0; i < this._impostors.length; ++i) {
  71674. if (this._impostors[i].physicsBody === body) {
  71675. return this._impostors[i];
  71676. }
  71677. }
  71678. return null;
  71679. };
  71680. // Statics
  71681. PhysicsEngine.Epsilon = 0.001;
  71682. return PhysicsEngine;
  71683. }());
  71684. BABYLON.PhysicsEngine = PhysicsEngine;
  71685. })(BABYLON || (BABYLON = {}));
  71686. //# sourceMappingURL=babylon.physicsEngine.js.map
  71687. var BABYLON;
  71688. (function (BABYLON) {
  71689. var PhysicsHelper = /** @class */ (function () {
  71690. function PhysicsHelper(scene) {
  71691. this._scene = scene;
  71692. this._physicsEngine = this._scene.getPhysicsEngine();
  71693. if (!this._physicsEngine) {
  71694. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  71695. }
  71696. }
  71697. /**
  71698. * @param {Vector3} origin the origin of the explosion
  71699. * @param {number} radius the explosion radius
  71700. * @param {number} strength the explosion strength
  71701. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71702. */
  71703. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  71704. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71705. if (!this._physicsEngine) {
  71706. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  71707. return null;
  71708. }
  71709. var impostors = this._physicsEngine.getImpostors();
  71710. if (impostors.length === 0) {
  71711. return null;
  71712. }
  71713. var event = new PhysicsRadialExplosionEvent(this._scene);
  71714. impostors.forEach(function (impostor) {
  71715. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71716. if (!impostorForceAndContactPoint) {
  71717. return;
  71718. }
  71719. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71720. });
  71721. event.dispose(false);
  71722. return event;
  71723. };
  71724. /**
  71725. * @param {Vector3} origin the origin of the explosion
  71726. * @param {number} radius the explosion radius
  71727. * @param {number} strength the explosion strength
  71728. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71729. */
  71730. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  71731. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71732. if (!this._physicsEngine) {
  71733. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71734. return null;
  71735. }
  71736. var impostors = this._physicsEngine.getImpostors();
  71737. if (impostors.length === 0) {
  71738. return null;
  71739. }
  71740. var event = new PhysicsRadialExplosionEvent(this._scene);
  71741. impostors.forEach(function (impostor) {
  71742. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71743. if (!impostorForceAndContactPoint) {
  71744. return;
  71745. }
  71746. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71747. });
  71748. event.dispose(false);
  71749. return event;
  71750. };
  71751. /**
  71752. * @param {Vector3} origin the origin of the explosion
  71753. * @param {number} radius the explosion radius
  71754. * @param {number} strength the explosion strength
  71755. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71756. */
  71757. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  71758. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71759. if (!this._physicsEngine) {
  71760. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71761. return null;
  71762. }
  71763. var impostors = this._physicsEngine.getImpostors();
  71764. if (impostors.length === 0) {
  71765. return null;
  71766. }
  71767. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  71768. event.dispose(false);
  71769. return event;
  71770. };
  71771. /**
  71772. * @param {Vector3} origin the origin of the updraft
  71773. * @param {number} radius the radius of the updraft
  71774. * @param {number} strength the strength of the updraft
  71775. * @param {number} height the height of the updraft
  71776. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  71777. */
  71778. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  71779. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  71780. if (!this._physicsEngine) {
  71781. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71782. return null;
  71783. }
  71784. if (this._physicsEngine.getImpostors().length === 0) {
  71785. return null;
  71786. }
  71787. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  71788. event.dispose(false);
  71789. return event;
  71790. };
  71791. /**
  71792. * @param {Vector3} origin the of the vortex
  71793. * @param {number} radius the radius of the vortex
  71794. * @param {number} strength the strength of the vortex
  71795. * @param {number} height the height of the vortex
  71796. */
  71797. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  71798. if (!this._physicsEngine) {
  71799. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71800. return null;
  71801. }
  71802. if (this._physicsEngine.getImpostors().length === 0) {
  71803. return null;
  71804. }
  71805. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  71806. event.dispose(false);
  71807. return event;
  71808. };
  71809. return PhysicsHelper;
  71810. }());
  71811. BABYLON.PhysicsHelper = PhysicsHelper;
  71812. /***** Radial explosion *****/
  71813. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  71814. function PhysicsRadialExplosionEvent(scene) {
  71815. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  71816. this._rays = [];
  71817. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  71818. this._scene = scene;
  71819. }
  71820. /**
  71821. * Returns the data related to the radial explosion event (sphere & rays).
  71822. * @returns {PhysicsRadialExplosionEventData}
  71823. */
  71824. PhysicsRadialExplosionEvent.prototype.getData = function () {
  71825. this._dataFetched = true;
  71826. return {
  71827. sphere: this._sphere,
  71828. rays: this._rays,
  71829. };
  71830. };
  71831. /**
  71832. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  71833. * @param impostor
  71834. * @param {Vector3} origin the origin of the explosion
  71835. * @param {number} radius the explosion radius
  71836. * @param {number} strength the explosion strength
  71837. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  71838. * @returns {Nullable<PhysicsForceAndContactPoint>}
  71839. */
  71840. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  71841. if (impostor.mass === 0) {
  71842. return null;
  71843. }
  71844. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  71845. return null;
  71846. }
  71847. if (impostor.object.getClassName() !== 'Mesh') {
  71848. return null;
  71849. }
  71850. var impostorObject = impostor.object;
  71851. var impostorObjectCenter = impostor.getObjectCenter();
  71852. var direction = impostorObjectCenter.subtract(origin);
  71853. var ray = new BABYLON.Ray(origin, direction, radius);
  71854. this._rays.push(ray);
  71855. var hit = ray.intersectsMesh(impostorObject);
  71856. var contactPoint = hit.pickedPoint;
  71857. if (!contactPoint) {
  71858. return null;
  71859. }
  71860. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  71861. if (distanceFromOrigin > radius) {
  71862. return null;
  71863. }
  71864. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  71865. ? strength
  71866. : strength * (1 - (distanceFromOrigin / radius));
  71867. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71868. return { force: force, contactPoint: contactPoint };
  71869. };
  71870. /**
  71871. * Disposes the sphere.
  71872. * @param {bolean} force
  71873. */
  71874. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  71875. var _this = this;
  71876. if (force === void 0) { force = true; }
  71877. if (force) {
  71878. this._sphere.dispose();
  71879. }
  71880. else {
  71881. setTimeout(function () {
  71882. if (!_this._dataFetched) {
  71883. _this._sphere.dispose();
  71884. }
  71885. }, 0);
  71886. }
  71887. };
  71888. /*** Helpers ***/
  71889. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  71890. if (!this._sphere) {
  71891. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  71892. this._sphere.isVisible = false;
  71893. }
  71894. };
  71895. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  71896. var impostorObject = impostor.object;
  71897. this._prepareSphere();
  71898. this._sphere.position = origin;
  71899. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  71900. this._sphere._updateBoundingInfo();
  71901. this._sphere.computeWorldMatrix(true);
  71902. return this._sphere.intersectsMesh(impostorObject, true);
  71903. };
  71904. return PhysicsRadialExplosionEvent;
  71905. }());
  71906. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  71907. /***** Gravitational Field *****/
  71908. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  71909. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  71910. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71911. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71912. this._physicsHelper = physicsHelper;
  71913. this._scene = scene;
  71914. this._origin = origin;
  71915. this._radius = radius;
  71916. this._strength = strength;
  71917. this._falloff = falloff;
  71918. this._tickCallback = this._tick.bind(this);
  71919. }
  71920. /**
  71921. * Returns the data related to the gravitational field event (sphere).
  71922. * @returns {PhysicsGravitationalFieldEventData}
  71923. */
  71924. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  71925. this._dataFetched = true;
  71926. return {
  71927. sphere: this._sphere,
  71928. };
  71929. };
  71930. /**
  71931. * Enables the gravitational field.
  71932. */
  71933. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  71934. this._tickCallback.call(this);
  71935. this._scene.registerBeforeRender(this._tickCallback);
  71936. };
  71937. /**
  71938. * Disables the gravitational field.
  71939. */
  71940. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  71941. this._scene.unregisterBeforeRender(this._tickCallback);
  71942. };
  71943. /**
  71944. * Disposes the sphere.
  71945. * @param {bolean} force
  71946. */
  71947. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  71948. var _this = this;
  71949. if (force === void 0) { force = true; }
  71950. if (force) {
  71951. this._sphere.dispose();
  71952. }
  71953. else {
  71954. setTimeout(function () {
  71955. if (!_this._dataFetched) {
  71956. _this._sphere.dispose();
  71957. }
  71958. }, 0);
  71959. }
  71960. };
  71961. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  71962. // Since the params won't change, we fetch the event only once
  71963. if (this._sphere) {
  71964. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71965. }
  71966. else {
  71967. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71968. if (radialExplosionEvent) {
  71969. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  71970. }
  71971. }
  71972. };
  71973. return PhysicsGravitationalFieldEvent;
  71974. }());
  71975. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  71976. /***** Updraft *****/
  71977. var PhysicsUpdraftEvent = /** @class */ (function () {
  71978. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  71979. this._scene = _scene;
  71980. this._origin = _origin;
  71981. this._radius = _radius;
  71982. this._strength = _strength;
  71983. this._height = _height;
  71984. this._updraftMode = _updraftMode;
  71985. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71986. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  71987. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71988. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71989. this._physicsEngine = this._scene.getPhysicsEngine();
  71990. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71991. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71992. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71993. this._originDirection = this._origin.subtract(this._originTop).normalize();
  71994. }
  71995. this._tickCallback = this._tick.bind(this);
  71996. }
  71997. /**
  71998. * Returns the data related to the updraft event (cylinder).
  71999. * @returns {PhysicsUpdraftEventData}
  72000. */
  72001. PhysicsUpdraftEvent.prototype.getData = function () {
  72002. this._dataFetched = true;
  72003. return {
  72004. cylinder: this._cylinder,
  72005. };
  72006. };
  72007. /**
  72008. * Enables the updraft.
  72009. */
  72010. PhysicsUpdraftEvent.prototype.enable = function () {
  72011. this._tickCallback.call(this);
  72012. this._scene.registerBeforeRender(this._tickCallback);
  72013. };
  72014. /**
  72015. * Disables the cortex.
  72016. */
  72017. PhysicsUpdraftEvent.prototype.disable = function () {
  72018. this._scene.unregisterBeforeRender(this._tickCallback);
  72019. };
  72020. /**
  72021. * Disposes the sphere.
  72022. * @param {bolean} force
  72023. */
  72024. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  72025. var _this = this;
  72026. if (force === void 0) { force = true; }
  72027. if (force) {
  72028. this._cylinder.dispose();
  72029. }
  72030. else {
  72031. setTimeout(function () {
  72032. if (!_this._dataFetched) {
  72033. _this._cylinder.dispose();
  72034. }
  72035. }, 0);
  72036. }
  72037. };
  72038. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72039. if (impostor.mass === 0) {
  72040. return null;
  72041. }
  72042. if (!this._intersectsWithCylinder(impostor)) {
  72043. return null;
  72044. }
  72045. var impostorObjectCenter = impostor.getObjectCenter();
  72046. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72047. var direction = this._originDirection;
  72048. }
  72049. else {
  72050. var direction = impostorObjectCenter.subtract(this._originTop);
  72051. }
  72052. var multiplier = this._strength * -1;
  72053. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72054. return { force: force, contactPoint: impostorObjectCenter };
  72055. };
  72056. PhysicsUpdraftEvent.prototype._tick = function () {
  72057. var _this = this;
  72058. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72059. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72060. if (!impostorForceAndContactPoint) {
  72061. return;
  72062. }
  72063. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72064. });
  72065. };
  72066. /*** Helpers ***/
  72067. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  72068. if (!this._cylinder) {
  72069. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  72070. height: this._height,
  72071. diameter: this._radius * 2,
  72072. }, this._scene);
  72073. this._cylinder.isVisible = false;
  72074. }
  72075. };
  72076. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  72077. var impostorObject = impostor.object;
  72078. this._prepareCylinder();
  72079. this._cylinder.position = this._cylinderPosition;
  72080. return this._cylinder.intersectsMesh(impostorObject, true);
  72081. };
  72082. return PhysicsUpdraftEvent;
  72083. }());
  72084. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  72085. /***** Vortex *****/
  72086. var PhysicsVortexEvent = /** @class */ (function () {
  72087. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  72088. this._scene = _scene;
  72089. this._origin = _origin;
  72090. this._radius = _radius;
  72091. this._strength = _strength;
  72092. this._height = _height;
  72093. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72094. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  72095. this._updraftMultiplier = 0.02;
  72096. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72097. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72098. this._physicsEngine = this._scene.getPhysicsEngine();
  72099. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72100. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72101. this._tickCallback = this._tick.bind(this);
  72102. }
  72103. /**
  72104. * Returns the data related to the vortex event (cylinder).
  72105. * @returns {PhysicsVortexEventData}
  72106. */
  72107. PhysicsVortexEvent.prototype.getData = function () {
  72108. this._dataFetched = true;
  72109. return {
  72110. cylinder: this._cylinder,
  72111. };
  72112. };
  72113. /**
  72114. * Enables the vortex.
  72115. */
  72116. PhysicsVortexEvent.prototype.enable = function () {
  72117. this._tickCallback.call(this);
  72118. this._scene.registerBeforeRender(this._tickCallback);
  72119. };
  72120. /**
  72121. * Disables the cortex.
  72122. */
  72123. PhysicsVortexEvent.prototype.disable = function () {
  72124. this._scene.unregisterBeforeRender(this._tickCallback);
  72125. };
  72126. /**
  72127. * Disposes the sphere.
  72128. * @param {bolean} force
  72129. */
  72130. PhysicsVortexEvent.prototype.dispose = function (force) {
  72131. var _this = this;
  72132. if (force === void 0) { force = true; }
  72133. if (force) {
  72134. this._cylinder.dispose();
  72135. }
  72136. else {
  72137. setTimeout(function () {
  72138. if (!_this._dataFetched) {
  72139. _this._cylinder.dispose();
  72140. }
  72141. }, 0);
  72142. }
  72143. };
  72144. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72145. if (impostor.mass === 0) {
  72146. return null;
  72147. }
  72148. if (!this._intersectsWithCylinder(impostor)) {
  72149. return null;
  72150. }
  72151. if (impostor.object.getClassName() !== 'Mesh') {
  72152. return null;
  72153. }
  72154. var impostorObject = impostor.object;
  72155. var impostorObjectCenter = impostor.getObjectCenter();
  72156. 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)
  72157. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  72158. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  72159. var hit = ray.intersectsMesh(impostorObject);
  72160. var contactPoint = hit.pickedPoint;
  72161. if (!contactPoint) {
  72162. return null;
  72163. }
  72164. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  72165. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  72166. var directionToOrigin = contactPoint.normalize();
  72167. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72168. directionToOrigin = directionToOrigin.negate();
  72169. }
  72170. // TODO: find a more physically based solution
  72171. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72172. var forceX = directionToOrigin.x * this._strength / 8;
  72173. var forceY = directionToOrigin.y * this._updraftMultiplier;
  72174. var forceZ = directionToOrigin.z * this._strength / 8;
  72175. }
  72176. else {
  72177. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  72178. var forceY = this._originTop.y * this._updraftMultiplier;
  72179. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  72180. }
  72181. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  72182. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  72183. return { force: force, contactPoint: impostorObjectCenter };
  72184. };
  72185. PhysicsVortexEvent.prototype._tick = function () {
  72186. var _this = this;
  72187. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72188. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72189. if (!impostorForceAndContactPoint) {
  72190. return;
  72191. }
  72192. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72193. });
  72194. };
  72195. /*** Helpers ***/
  72196. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  72197. if (!this._cylinder) {
  72198. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  72199. height: this._height,
  72200. diameter: this._radius * 2,
  72201. }, this._scene);
  72202. this._cylinder.isVisible = false;
  72203. }
  72204. };
  72205. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  72206. var impostorObject = impostor.object;
  72207. this._prepareCylinder();
  72208. this._cylinder.position = this._cylinderPosition;
  72209. return this._cylinder.intersectsMesh(impostorObject, true);
  72210. };
  72211. return PhysicsVortexEvent;
  72212. }());
  72213. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  72214. /***** Enums *****/
  72215. /**
  72216. * The strenght of the force in correspondence to the distance of the affected object
  72217. */
  72218. var PhysicsRadialImpulseFalloff;
  72219. (function (PhysicsRadialImpulseFalloff) {
  72220. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  72221. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  72222. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  72223. /**
  72224. * The strenght of the force in correspondence to the distance of the affected object
  72225. */
  72226. var PhysicsUpdraftMode;
  72227. (function (PhysicsUpdraftMode) {
  72228. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  72229. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  72230. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  72231. })(BABYLON || (BABYLON = {}));
  72232. //# sourceMappingURL=babylon.physicsHelper.js.map
  72233. var BABYLON;
  72234. (function (BABYLON) {
  72235. var CannonJSPlugin = /** @class */ (function () {
  72236. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  72237. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  72238. if (iterations === void 0) { iterations = 10; }
  72239. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  72240. this.name = "CannonJSPlugin";
  72241. this._physicsMaterials = new Array();
  72242. this._fixedTimeStep = 1 / 60;
  72243. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  72244. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  72245. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  72246. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  72247. this._tmpPosition = BABYLON.Vector3.Zero();
  72248. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  72249. this._tmpUnityRotation = new BABYLON.Quaternion();
  72250. if (!this.isSupported()) {
  72251. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  72252. return;
  72253. }
  72254. this._extendNamespace();
  72255. this.world = new this.BJSCANNON.World();
  72256. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  72257. this.world.solver.iterations = iterations;
  72258. }
  72259. CannonJSPlugin.prototype.setGravity = function (gravity) {
  72260. this.world.gravity.copy(gravity);
  72261. };
  72262. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  72263. this._fixedTimeStep = timeStep;
  72264. };
  72265. CannonJSPlugin.prototype.getTimeStep = function () {
  72266. return this._fixedTimeStep;
  72267. };
  72268. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  72269. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  72270. };
  72271. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72272. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72273. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72274. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  72275. };
  72276. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72277. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72278. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72279. impostor.physicsBody.applyForce(impulse, worldPoint);
  72280. };
  72281. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72282. //parent-child relationship. Does this impostor has a parent impostor?
  72283. if (impostor.parent) {
  72284. if (impostor.physicsBody) {
  72285. this.removePhysicsBody(impostor);
  72286. //TODO is that needed?
  72287. impostor.forceUpdate();
  72288. }
  72289. return;
  72290. }
  72291. //should a new body be created for this impostor?
  72292. if (impostor.isBodyInitRequired()) {
  72293. var shape = this._createShape(impostor);
  72294. //unregister events, if body is being changed
  72295. var oldBody = impostor.physicsBody;
  72296. if (oldBody) {
  72297. this.removePhysicsBody(impostor);
  72298. }
  72299. //create the body and material
  72300. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  72301. var bodyCreationObject = {
  72302. mass: impostor.getParam("mass"),
  72303. material: material
  72304. };
  72305. // A simple extend, in case native options were used.
  72306. var nativeOptions = impostor.getParam("nativeOptions");
  72307. for (var key in nativeOptions) {
  72308. if (nativeOptions.hasOwnProperty(key)) {
  72309. bodyCreationObject[key] = nativeOptions[key];
  72310. }
  72311. }
  72312. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  72313. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  72314. this.world.addEventListener("preStep", impostor.beforeStep);
  72315. this.world.addEventListener("postStep", impostor.afterStep);
  72316. impostor.physicsBody.addShape(shape);
  72317. this.world.add(impostor.physicsBody);
  72318. //try to keep the body moving in the right direction by taking old properties.
  72319. //Should be tested!
  72320. if (oldBody) {
  72321. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  72322. impostor.physicsBody[param].copy(oldBody[param]);
  72323. });
  72324. }
  72325. this._processChildMeshes(impostor);
  72326. }
  72327. //now update the body's transformation
  72328. this._updatePhysicsBodyTransformation(impostor);
  72329. };
  72330. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  72331. var _this = this;
  72332. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  72333. var currentRotation = mainImpostor.object.rotationQuaternion;
  72334. if (meshChildren.length) {
  72335. var processMesh = function (localPosition, mesh) {
  72336. if (!currentRotation || !mesh.rotationQuaternion) {
  72337. return;
  72338. }
  72339. var childImpostor = mesh.getPhysicsImpostor();
  72340. if (childImpostor) {
  72341. var parent = childImpostor.parent;
  72342. if (parent !== mainImpostor) {
  72343. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  72344. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  72345. if (childImpostor.physicsBody) {
  72346. _this.removePhysicsBody(childImpostor);
  72347. childImpostor.physicsBody = null;
  72348. }
  72349. childImpostor.parent = mainImpostor;
  72350. childImpostor.resetUpdateFlags();
  72351. 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));
  72352. //Add the mass of the children.
  72353. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  72354. }
  72355. }
  72356. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  72357. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  72358. };
  72359. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  72360. }
  72361. };
  72362. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72363. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  72364. this.world.removeEventListener("preStep", impostor.beforeStep);
  72365. this.world.removeEventListener("postStep", impostor.afterStep);
  72366. this.world.remove(impostor.physicsBody);
  72367. };
  72368. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72369. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72370. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72371. if (!mainBody || !connectedBody) {
  72372. return;
  72373. }
  72374. var constraint;
  72375. var jointData = impostorJoint.joint.jointData;
  72376. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  72377. var constraintData = {
  72378. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  72379. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  72380. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  72381. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  72382. maxForce: jointData.nativeParams.maxForce,
  72383. collideConnected: !!jointData.collision
  72384. };
  72385. switch (impostorJoint.joint.type) {
  72386. case BABYLON.PhysicsJoint.HingeJoint:
  72387. case BABYLON.PhysicsJoint.Hinge2Joint:
  72388. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  72389. break;
  72390. case BABYLON.PhysicsJoint.DistanceJoint:
  72391. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  72392. break;
  72393. case BABYLON.PhysicsJoint.SpringJoint:
  72394. var springData = jointData;
  72395. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  72396. restLength: springData.length,
  72397. stiffness: springData.stiffness,
  72398. damping: springData.damping,
  72399. localAnchorA: constraintData.pivotA,
  72400. localAnchorB: constraintData.pivotB
  72401. });
  72402. break;
  72403. case BABYLON.PhysicsJoint.LockJoint:
  72404. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  72405. break;
  72406. case BABYLON.PhysicsJoint.PointToPointJoint:
  72407. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72408. default:
  72409. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  72410. break;
  72411. }
  72412. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  72413. constraint.collideConnected = !!jointData.collision;
  72414. impostorJoint.joint.physicsJoint = constraint;
  72415. //don't add spring as constraint, as it is not one.
  72416. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  72417. this.world.addConstraint(constraint);
  72418. }
  72419. else {
  72420. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  72421. constraint.applyForce();
  72422. });
  72423. }
  72424. };
  72425. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72426. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  72427. };
  72428. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  72429. var index;
  72430. var mat;
  72431. for (index = 0; index < this._physicsMaterials.length; index++) {
  72432. mat = this._physicsMaterials[index];
  72433. if (mat.friction === friction && mat.restitution === restitution) {
  72434. return mat;
  72435. }
  72436. }
  72437. var currentMat = new this.BJSCANNON.Material(name);
  72438. currentMat.friction = friction;
  72439. currentMat.restitution = restitution;
  72440. this._physicsMaterials.push(currentMat);
  72441. return currentMat;
  72442. };
  72443. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  72444. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  72445. };
  72446. CannonJSPlugin.prototype._createShape = function (impostor) {
  72447. var object = impostor.object;
  72448. var returnValue;
  72449. var extendSize = impostor.getObjectExtendSize();
  72450. switch (impostor.type) {
  72451. case BABYLON.PhysicsImpostor.SphereImpostor:
  72452. var radiusX = extendSize.x;
  72453. var radiusY = extendSize.y;
  72454. var radiusZ = extendSize.z;
  72455. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  72456. break;
  72457. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  72458. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72459. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  72460. break;
  72461. case BABYLON.PhysicsImpostor.BoxImpostor:
  72462. var box = extendSize.scale(0.5);
  72463. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  72464. break;
  72465. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72466. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  72467. returnValue = new this.BJSCANNON.Plane();
  72468. break;
  72469. case BABYLON.PhysicsImpostor.MeshImpostor:
  72470. // should transform the vertex data to world coordinates!!
  72471. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  72472. var rawFaces = object.getIndices ? object.getIndices() : [];
  72473. if (!rawVerts)
  72474. return;
  72475. // get only scale! so the object could transform correctly.
  72476. var oldPosition = object.position.clone();
  72477. var oldRotation = object.rotation && object.rotation.clone();
  72478. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  72479. object.position.copyFromFloats(0, 0, 0);
  72480. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72481. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72482. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72483. var transform = object.computeWorldMatrix(true);
  72484. // convert rawVerts to object space
  72485. var temp = new Array();
  72486. var index;
  72487. for (index = 0; index < rawVerts.length; index += 3) {
  72488. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  72489. }
  72490. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  72491. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  72492. //now set back the transformation!
  72493. object.position.copyFrom(oldPosition);
  72494. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  72495. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  72496. break;
  72497. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  72498. var oldPosition2 = object.position.clone();
  72499. var oldRotation2 = object.rotation && object.rotation.clone();
  72500. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  72501. object.position.copyFromFloats(0, 0, 0);
  72502. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72503. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72504. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72505. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  72506. returnValue = this._createHeightmap(object);
  72507. object.position.copyFrom(oldPosition2);
  72508. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  72509. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  72510. object.computeWorldMatrix(true);
  72511. break;
  72512. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72513. returnValue = new this.BJSCANNON.Particle();
  72514. break;
  72515. }
  72516. return returnValue;
  72517. };
  72518. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  72519. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  72520. var transform = object.computeWorldMatrix(true);
  72521. // convert rawVerts to object space
  72522. var temp = new Array();
  72523. var index;
  72524. for (index = 0; index < pos.length; index += 3) {
  72525. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  72526. }
  72527. pos = temp;
  72528. var matrix = new Array();
  72529. //For now pointDepth will not be used and will be automatically calculated.
  72530. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  72531. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  72532. var boundingInfo = object.getBoundingInfo();
  72533. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  72534. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  72535. var elementSize = dim * 2 / arraySize;
  72536. for (var i = 0; i < pos.length; i = i + 3) {
  72537. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  72538. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  72539. var y = -pos[i + 2] + minY;
  72540. if (!matrix[x]) {
  72541. matrix[x] = [];
  72542. }
  72543. if (!matrix[x][z]) {
  72544. matrix[x][z] = y;
  72545. }
  72546. matrix[x][z] = Math.max(y, matrix[x][z]);
  72547. }
  72548. for (var x = 0; x <= arraySize; ++x) {
  72549. if (!matrix[x]) {
  72550. var loc = 1;
  72551. while (!matrix[(x + loc) % arraySize]) {
  72552. loc++;
  72553. }
  72554. matrix[x] = matrix[(x + loc) % arraySize].slice();
  72555. //console.log("missing x", x);
  72556. }
  72557. for (var z = 0; z <= arraySize; ++z) {
  72558. if (!matrix[x][z]) {
  72559. var loc = 1;
  72560. var newValue;
  72561. while (newValue === undefined) {
  72562. newValue = matrix[x][(z + loc++) % arraySize];
  72563. }
  72564. matrix[x][z] = newValue;
  72565. }
  72566. }
  72567. }
  72568. var shape = new this.BJSCANNON.Heightfield(matrix, {
  72569. elementSize: elementSize
  72570. });
  72571. //For future reference, needed for body transformation
  72572. shape.minY = minY;
  72573. return shape;
  72574. };
  72575. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  72576. var object = impostor.object;
  72577. //make sure it is updated...
  72578. object.computeWorldMatrix && object.computeWorldMatrix(true);
  72579. // The delta between the mesh position and the mesh bounding box center
  72580. var bInfo = object.getBoundingInfo();
  72581. if (!bInfo)
  72582. return;
  72583. var center = impostor.getObjectCenter();
  72584. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  72585. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  72586. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  72587. this._tmpPosition.copyFrom(center);
  72588. var quaternion = object.rotationQuaternion;
  72589. if (!quaternion) {
  72590. return;
  72591. }
  72592. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  72593. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  72594. //-90 DEG in X, precalculated
  72595. quaternion = quaternion.multiply(this._minus90X);
  72596. //Invert! (Precalculated, 90 deg in X)
  72597. //No need to clone. this will never change.
  72598. impostor.setDeltaRotation(this._plus90X);
  72599. }
  72600. //If it is a heightfield, if should be centered.
  72601. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  72602. var mesh = object;
  72603. var boundingInfo = mesh.getBoundingInfo();
  72604. //calculate the correct body position:
  72605. var rotationQuaternion = mesh.rotationQuaternion;
  72606. mesh.rotationQuaternion = this._tmpUnityRotation;
  72607. mesh.computeWorldMatrix(true);
  72608. //get original center with no rotation
  72609. var c = center.clone();
  72610. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  72611. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  72612. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  72613. mesh.setPivotMatrix(p);
  72614. mesh.computeWorldMatrix(true);
  72615. //calculate the translation
  72616. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  72617. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  72618. //add it inverted to the delta
  72619. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  72620. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  72621. //rotation is back
  72622. mesh.rotationQuaternion = rotationQuaternion;
  72623. mesh.setPivotMatrix(oldPivot);
  72624. mesh.computeWorldMatrix(true);
  72625. }
  72626. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  72627. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  72628. //this._tmpPosition.copyFrom(object.position);
  72629. }
  72630. impostor.setDeltaPosition(this._tmpDeltaPosition);
  72631. //Now update the impostor object
  72632. impostor.physicsBody.position.copy(this._tmpPosition);
  72633. impostor.physicsBody.quaternion.copy(quaternion);
  72634. };
  72635. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72636. impostor.object.position.copyFrom(impostor.physicsBody.position);
  72637. if (impostor.object.rotationQuaternion) {
  72638. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  72639. }
  72640. };
  72641. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72642. impostor.physicsBody.position.copy(newPosition);
  72643. impostor.physicsBody.quaternion.copy(newRotation);
  72644. };
  72645. CannonJSPlugin.prototype.isSupported = function () {
  72646. return this.BJSCANNON !== undefined;
  72647. };
  72648. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72649. impostor.physicsBody.velocity.copy(velocity);
  72650. };
  72651. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72652. impostor.physicsBody.angularVelocity.copy(velocity);
  72653. };
  72654. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72655. var v = impostor.physicsBody.velocity;
  72656. if (!v) {
  72657. return null;
  72658. }
  72659. return new BABYLON.Vector3(v.x, v.y, v.z);
  72660. };
  72661. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72662. var v = impostor.physicsBody.angularVelocity;
  72663. if (!v) {
  72664. return null;
  72665. }
  72666. return new BABYLON.Vector3(v.x, v.y, v.z);
  72667. };
  72668. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72669. impostor.physicsBody.mass = mass;
  72670. impostor.physicsBody.updateMassProperties();
  72671. };
  72672. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  72673. return impostor.physicsBody.mass;
  72674. };
  72675. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  72676. return impostor.physicsBody.material.friction;
  72677. };
  72678. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72679. impostor.physicsBody.material.friction = friction;
  72680. };
  72681. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72682. return impostor.physicsBody.material.restitution;
  72683. };
  72684. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72685. impostor.physicsBody.material.restitution = restitution;
  72686. };
  72687. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  72688. impostor.physicsBody.sleep();
  72689. };
  72690. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  72691. impostor.physicsBody.wakeUp();
  72692. };
  72693. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72694. joint.physicsJoint.distance = maxDistance;
  72695. };
  72696. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72697. // if (!motorIndex) {
  72698. // joint.physicsJoint.enableMotor();
  72699. // }
  72700. // }
  72701. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72702. // if (!motorIndex) {
  72703. // joint.physicsJoint.disableMotor();
  72704. // }
  72705. // }
  72706. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72707. if (!motorIndex) {
  72708. joint.physicsJoint.enableMotor();
  72709. joint.physicsJoint.setMotorSpeed(speed);
  72710. if (maxForce) {
  72711. this.setLimit(joint, maxForce);
  72712. }
  72713. }
  72714. };
  72715. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  72716. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  72717. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  72718. };
  72719. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72720. var body = impostor.physicsBody;
  72721. mesh.position.x = body.position.x;
  72722. mesh.position.y = body.position.y;
  72723. mesh.position.z = body.position.z;
  72724. if (mesh.rotationQuaternion) {
  72725. mesh.rotationQuaternion.x = body.quaternion.x;
  72726. mesh.rotationQuaternion.y = body.quaternion.y;
  72727. mesh.rotationQuaternion.z = body.quaternion.z;
  72728. mesh.rotationQuaternion.w = body.quaternion.w;
  72729. }
  72730. };
  72731. CannonJSPlugin.prototype.getRadius = function (impostor) {
  72732. var shape = impostor.physicsBody.shapes[0];
  72733. return shape.boundingSphereRadius;
  72734. };
  72735. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72736. var shape = impostor.physicsBody.shapes[0];
  72737. result.x = shape.halfExtents.x * 2;
  72738. result.y = shape.halfExtents.y * 2;
  72739. result.z = shape.halfExtents.z * 2;
  72740. };
  72741. CannonJSPlugin.prototype.dispose = function () {
  72742. };
  72743. CannonJSPlugin.prototype._extendNamespace = function () {
  72744. //this will force cannon to execute at least one step when using interpolation
  72745. var step_tmp1 = new this.BJSCANNON.Vec3();
  72746. var Engine = this.BJSCANNON;
  72747. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  72748. maxSubSteps = maxSubSteps || 10;
  72749. timeSinceLastCalled = timeSinceLastCalled || 0;
  72750. if (timeSinceLastCalled === 0) {
  72751. this.internalStep(dt);
  72752. this.time += dt;
  72753. }
  72754. else {
  72755. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  72756. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  72757. var t0 = performance.now();
  72758. for (var i = 0; i !== internalSteps; i++) {
  72759. this.internalStep(dt);
  72760. if (performance.now() - t0 > dt * 1000) {
  72761. break;
  72762. }
  72763. }
  72764. this.time += timeSinceLastCalled;
  72765. var h = this.time % dt;
  72766. var h_div_dt = h / dt;
  72767. var interpvelo = step_tmp1;
  72768. var bodies = this.bodies;
  72769. for (var j = 0; j !== bodies.length; j++) {
  72770. var b = bodies[j];
  72771. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  72772. b.position.vsub(b.previousPosition, interpvelo);
  72773. interpvelo.scale(h_div_dt, interpvelo);
  72774. b.position.vadd(interpvelo, b.interpolatedPosition);
  72775. }
  72776. else {
  72777. b.interpolatedPosition.copy(b.position);
  72778. b.interpolatedQuaternion.copy(b.quaternion);
  72779. }
  72780. }
  72781. }
  72782. };
  72783. };
  72784. return CannonJSPlugin;
  72785. }());
  72786. BABYLON.CannonJSPlugin = CannonJSPlugin;
  72787. })(BABYLON || (BABYLON = {}));
  72788. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  72789. var BABYLON;
  72790. (function (BABYLON) {
  72791. var OimoJSPlugin = /** @class */ (function () {
  72792. function OimoJSPlugin(iterations) {
  72793. this.name = "OimoJSPlugin";
  72794. this._tmpImpostorsArray = [];
  72795. this._tmpPositionVector = BABYLON.Vector3.Zero();
  72796. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  72797. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  72798. this.world.worldscale(1);
  72799. this.world.clear();
  72800. //making sure no stats are calculated
  72801. this.world.isNoStat = true;
  72802. }
  72803. OimoJSPlugin.prototype.setGravity = function (gravity) {
  72804. this.world.gravity.copy(gravity);
  72805. };
  72806. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  72807. this.world.timeStep = timeStep;
  72808. };
  72809. OimoJSPlugin.prototype.getTimeStep = function () {
  72810. return this.world.timeStep;
  72811. };
  72812. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  72813. var _this = this;
  72814. impostors.forEach(function (impostor) {
  72815. impostor.beforeStep();
  72816. });
  72817. this.world.step();
  72818. impostors.forEach(function (impostor) {
  72819. impostor.afterStep();
  72820. //update the ordered impostors array
  72821. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  72822. });
  72823. //check for collisions
  72824. var contact = this.world.contacts;
  72825. while (contact !== null) {
  72826. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  72827. contact = contact.next;
  72828. continue;
  72829. }
  72830. //is this body colliding with any other? get the impostor
  72831. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  72832. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  72833. if (!mainImpostor || !collidingImpostor) {
  72834. contact = contact.next;
  72835. continue;
  72836. }
  72837. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  72838. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  72839. contact = contact.next;
  72840. }
  72841. };
  72842. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72843. var mass = impostor.physicsBody.massInfo.mass;
  72844. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  72845. };
  72846. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72847. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  72848. this.applyImpulse(impostor, force, contactPoint);
  72849. };
  72850. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72851. var _this = this;
  72852. //parent-child relationship. Does this impostor has a parent impostor?
  72853. if (impostor.parent) {
  72854. if (impostor.physicsBody) {
  72855. this.removePhysicsBody(impostor);
  72856. //TODO is that needed?
  72857. impostor.forceUpdate();
  72858. }
  72859. return;
  72860. }
  72861. if (impostor.isBodyInitRequired()) {
  72862. var bodyConfig = {
  72863. name: impostor.uniqueId,
  72864. //Oimo must have mass, also for static objects.
  72865. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72866. size: [],
  72867. type: [],
  72868. pos: [],
  72869. rot: [],
  72870. move: impostor.getParam("mass") !== 0,
  72871. //Supporting older versions of Oimo
  72872. world: this.world
  72873. };
  72874. var impostors = [impostor];
  72875. var addToArray = function (parent) {
  72876. if (!parent.getChildMeshes)
  72877. return;
  72878. parent.getChildMeshes().forEach(function (m) {
  72879. if (m.physicsImpostor) {
  72880. impostors.push(m.physicsImpostor);
  72881. //m.physicsImpostor._init();
  72882. }
  72883. });
  72884. };
  72885. addToArray(impostor.object);
  72886. var checkWithEpsilon_1 = function (value) {
  72887. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  72888. };
  72889. impostors.forEach(function (i) {
  72890. if (!impostor.object.rotationQuaternion) {
  72891. return;
  72892. }
  72893. //get the correct bounding box
  72894. var oldQuaternion = i.object.rotationQuaternion;
  72895. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  72896. x: impostor.object.rotationQuaternion.x,
  72897. y: impostor.object.rotationQuaternion.y,
  72898. z: impostor.object.rotationQuaternion.z,
  72899. s: impostor.object.rotationQuaternion.w
  72900. });
  72901. var extendSize = i.getObjectExtendSize();
  72902. if (i === impostor) {
  72903. var center = impostor.getObjectCenter();
  72904. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  72905. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  72906. //Can also use Array.prototype.push.apply
  72907. bodyConfig.pos.push(center.x);
  72908. bodyConfig.pos.push(center.y);
  72909. bodyConfig.pos.push(center.z);
  72910. //tmp solution
  72911. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72912. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72913. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72914. }
  72915. else {
  72916. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  72917. bodyConfig.pos.push(localPosition.x);
  72918. bodyConfig.pos.push(localPosition.y);
  72919. bodyConfig.pos.push(localPosition.z);
  72920. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  72921. bodyConfig.rot.push(0);
  72922. bodyConfig.rot.push(0);
  72923. bodyConfig.rot.push(0);
  72924. }
  72925. // register mesh
  72926. switch (i.type) {
  72927. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72928. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  72929. case BABYLON.PhysicsImpostor.SphereImpostor:
  72930. var radiusX = extendSize.x;
  72931. var radiusY = extendSize.y;
  72932. var radiusZ = extendSize.z;
  72933. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  72934. bodyConfig.type.push('sphere');
  72935. //due to the way oimo works with compounds, add 3 times
  72936. bodyConfig.size.push(size);
  72937. bodyConfig.size.push(size);
  72938. bodyConfig.size.push(size);
  72939. break;
  72940. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72941. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  72942. var sizeY = checkWithEpsilon_1(extendSize.y);
  72943. bodyConfig.type.push('cylinder');
  72944. bodyConfig.size.push(sizeX);
  72945. bodyConfig.size.push(sizeY);
  72946. //due to the way oimo works with compounds, add one more value.
  72947. bodyConfig.size.push(sizeY);
  72948. break;
  72949. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72950. case BABYLON.PhysicsImpostor.BoxImpostor:
  72951. default:
  72952. var sizeX = checkWithEpsilon_1(extendSize.x);
  72953. var sizeY = checkWithEpsilon_1(extendSize.y);
  72954. var sizeZ = checkWithEpsilon_1(extendSize.z);
  72955. bodyConfig.type.push('box');
  72956. bodyConfig.size.push(sizeX);
  72957. bodyConfig.size.push(sizeY);
  72958. bodyConfig.size.push(sizeZ);
  72959. break;
  72960. }
  72961. //actually not needed, but hey...
  72962. i.object.rotationQuaternion = oldQuaternion;
  72963. });
  72964. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  72965. }
  72966. else {
  72967. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  72968. }
  72969. impostor.setDeltaPosition(this._tmpPositionVector);
  72970. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  72971. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  72972. };
  72973. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72974. //impostor.physicsBody.dispose();
  72975. //Same as : (older oimo versions)
  72976. this.world.removeRigidBody(impostor.physicsBody);
  72977. };
  72978. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72979. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72980. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72981. if (!mainBody || !connectedBody) {
  72982. return;
  72983. }
  72984. var jointData = impostorJoint.joint.jointData;
  72985. var options = jointData.nativeParams || {};
  72986. var type;
  72987. var nativeJointData = {
  72988. body1: mainBody,
  72989. body2: connectedBody,
  72990. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  72991. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  72992. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  72993. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  72994. min: options.min,
  72995. max: options.max,
  72996. collision: options.collision || jointData.collision,
  72997. spring: options.spring,
  72998. //supporting older version of Oimo
  72999. world: this.world
  73000. };
  73001. switch (impostorJoint.joint.type) {
  73002. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  73003. type = "jointBall";
  73004. break;
  73005. case BABYLON.PhysicsJoint.SpringJoint:
  73006. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  73007. var springData = jointData;
  73008. nativeJointData.min = springData.length || nativeJointData.min;
  73009. //Max should also be set, just make sure it is at least min
  73010. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  73011. case BABYLON.PhysicsJoint.DistanceJoint:
  73012. type = "jointDistance";
  73013. nativeJointData.max = jointData.maxDistance;
  73014. break;
  73015. case BABYLON.PhysicsJoint.PrismaticJoint:
  73016. type = "jointPrisme";
  73017. break;
  73018. case BABYLON.PhysicsJoint.SliderJoint:
  73019. type = "jointSlide";
  73020. break;
  73021. case BABYLON.PhysicsJoint.WheelJoint:
  73022. type = "jointWheel";
  73023. break;
  73024. case BABYLON.PhysicsJoint.HingeJoint:
  73025. default:
  73026. type = "jointHinge";
  73027. break;
  73028. }
  73029. nativeJointData.type = type;
  73030. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  73031. };
  73032. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  73033. //Bug in Oimo prevents us from disposing a joint in the playground
  73034. //joint.joint.physicsJoint.dispose();
  73035. //So we will bruteforce it!
  73036. try {
  73037. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  73038. }
  73039. catch (e) {
  73040. BABYLON.Tools.Warn(e);
  73041. }
  73042. };
  73043. OimoJSPlugin.prototype.isSupported = function () {
  73044. return this.BJSOIMO !== undefined;
  73045. };
  73046. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73047. if (!impostor.physicsBody.sleeping) {
  73048. //TODO check that
  73049. if (impostor.physicsBody.shapes.next) {
  73050. var parentShape = this._getLastShape(impostor.physicsBody);
  73051. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  73052. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  73053. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  73054. }
  73055. else {
  73056. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  73057. }
  73058. if (impostor.object.rotationQuaternion) {
  73059. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  73060. impostor.object.rotationQuaternion.normalize();
  73061. }
  73062. }
  73063. };
  73064. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73065. var body = impostor.physicsBody;
  73066. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  73067. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  73068. body.syncShapes();
  73069. body.awake();
  73070. };
  73071. OimoJSPlugin.prototype._getLastShape = function (body) {
  73072. var lastShape = body.shapes;
  73073. while (lastShape.next) {
  73074. lastShape = lastShape.next;
  73075. }
  73076. return lastShape;
  73077. };
  73078. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73079. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  73080. };
  73081. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73082. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  73083. };
  73084. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73085. var v = impostor.physicsBody.linearVelocity;
  73086. if (!v) {
  73087. return null;
  73088. }
  73089. return new BABYLON.Vector3(v.x, v.y, v.z);
  73090. };
  73091. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73092. var v = impostor.physicsBody.angularVelocity;
  73093. if (!v) {
  73094. return null;
  73095. }
  73096. return new BABYLON.Vector3(v.x, v.y, v.z);
  73097. };
  73098. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73099. var staticBody = mass === 0;
  73100. //this will actually set the body's density and not its mass.
  73101. //But this is how oimo treats the mass variable.
  73102. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  73103. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  73104. };
  73105. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  73106. return impostor.physicsBody.shapes.density;
  73107. };
  73108. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  73109. return impostor.physicsBody.shapes.friction;
  73110. };
  73111. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73112. impostor.physicsBody.shapes.friction = friction;
  73113. };
  73114. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73115. return impostor.physicsBody.shapes.restitution;
  73116. };
  73117. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73118. impostor.physicsBody.shapes.restitution = restitution;
  73119. };
  73120. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  73121. impostor.physicsBody.sleep();
  73122. };
  73123. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  73124. impostor.physicsBody.awake();
  73125. };
  73126. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73127. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  73128. if (minDistance !== void 0) {
  73129. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  73130. }
  73131. };
  73132. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73133. //TODO separate rotational and transational motors.
  73134. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73135. if (motor) {
  73136. motor.setMotor(speed, maxForce);
  73137. }
  73138. };
  73139. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  73140. //TODO separate rotational and transational motors.
  73141. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73142. if (motor) {
  73143. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  73144. }
  73145. };
  73146. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73147. var body = impostor.physicsBody;
  73148. mesh.position.x = body.position.x;
  73149. mesh.position.y = body.position.y;
  73150. mesh.position.z = body.position.z;
  73151. if (mesh.rotationQuaternion) {
  73152. mesh.rotationQuaternion.x = body.orientation.x;
  73153. mesh.rotationQuaternion.y = body.orientation.y;
  73154. mesh.rotationQuaternion.z = body.orientation.z;
  73155. mesh.rotationQuaternion.w = body.orientation.s;
  73156. }
  73157. };
  73158. OimoJSPlugin.prototype.getRadius = function (impostor) {
  73159. return impostor.physicsBody.shapes.radius;
  73160. };
  73161. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73162. var shape = impostor.physicsBody.shapes;
  73163. result.x = shape.halfWidth * 2;
  73164. result.y = shape.halfHeight * 2;
  73165. result.z = shape.halfDepth * 2;
  73166. };
  73167. OimoJSPlugin.prototype.dispose = function () {
  73168. this.world.clear();
  73169. };
  73170. return OimoJSPlugin;
  73171. }());
  73172. BABYLON.OimoJSPlugin = OimoJSPlugin;
  73173. })(BABYLON || (BABYLON = {}));
  73174. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  73175. var BABYLON;
  73176. (function (BABYLON) {
  73177. /*
  73178. * Based on jsTGALoader - Javascript loader for TGA file
  73179. * By Vincent Thibault
  73180. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  73181. */
  73182. var TGATools = /** @class */ (function () {
  73183. function TGATools() {
  73184. }
  73185. TGATools.GetTGAHeader = function (data) {
  73186. var offset = 0;
  73187. var header = {
  73188. id_length: data[offset++],
  73189. colormap_type: data[offset++],
  73190. image_type: data[offset++],
  73191. colormap_index: data[offset++] | data[offset++] << 8,
  73192. colormap_length: data[offset++] | data[offset++] << 8,
  73193. colormap_size: data[offset++],
  73194. origin: [
  73195. data[offset++] | data[offset++] << 8,
  73196. data[offset++] | data[offset++] << 8
  73197. ],
  73198. width: data[offset++] | data[offset++] << 8,
  73199. height: data[offset++] | data[offset++] << 8,
  73200. pixel_size: data[offset++],
  73201. flags: data[offset++]
  73202. };
  73203. return header;
  73204. };
  73205. TGATools.UploadContent = function (gl, data) {
  73206. // Not enough data to contain header ?
  73207. if (data.length < 19) {
  73208. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  73209. return;
  73210. }
  73211. // Read Header
  73212. var offset = 18;
  73213. var header = TGATools.GetTGAHeader(data);
  73214. // Assume it's a valid Targa file.
  73215. if (header.id_length + offset > data.length) {
  73216. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  73217. return;
  73218. }
  73219. // Skip not needed data
  73220. offset += header.id_length;
  73221. var use_rle = false;
  73222. var use_pal = false;
  73223. var use_grey = false;
  73224. // Get some informations.
  73225. switch (header.image_type) {
  73226. case TGATools._TYPE_RLE_INDEXED:
  73227. use_rle = true;
  73228. case TGATools._TYPE_INDEXED:
  73229. use_pal = true;
  73230. break;
  73231. case TGATools._TYPE_RLE_RGB:
  73232. use_rle = true;
  73233. case TGATools._TYPE_RGB:
  73234. // use_rgb = true;
  73235. break;
  73236. case TGATools._TYPE_RLE_GREY:
  73237. use_rle = true;
  73238. case TGATools._TYPE_GREY:
  73239. use_grey = true;
  73240. break;
  73241. }
  73242. var pixel_data;
  73243. // var numAlphaBits = header.flags & 0xf;
  73244. var pixel_size = header.pixel_size >> 3;
  73245. var pixel_total = header.width * header.height * pixel_size;
  73246. // Read palettes
  73247. var palettes;
  73248. if (use_pal) {
  73249. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  73250. }
  73251. // Read LRE
  73252. if (use_rle) {
  73253. pixel_data = new Uint8Array(pixel_total);
  73254. var c, count, i;
  73255. var localOffset = 0;
  73256. var pixels = new Uint8Array(pixel_size);
  73257. while (offset < pixel_total && localOffset < pixel_total) {
  73258. c = data[offset++];
  73259. count = (c & 0x7f) + 1;
  73260. // RLE pixels
  73261. if (c & 0x80) {
  73262. // Bind pixel tmp array
  73263. for (i = 0; i < pixel_size; ++i) {
  73264. pixels[i] = data[offset++];
  73265. }
  73266. // Copy pixel array
  73267. for (i = 0; i < count; ++i) {
  73268. pixel_data.set(pixels, localOffset + i * pixel_size);
  73269. }
  73270. localOffset += pixel_size * count;
  73271. }
  73272. else {
  73273. count *= pixel_size;
  73274. for (i = 0; i < count; ++i) {
  73275. pixel_data[localOffset + i] = data[offset++];
  73276. }
  73277. localOffset += count;
  73278. }
  73279. }
  73280. }
  73281. else {
  73282. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  73283. }
  73284. // Load to texture
  73285. var x_start, y_start, x_step, y_step, y_end, x_end;
  73286. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  73287. default:
  73288. case TGATools._ORIGIN_UL:
  73289. x_start = 0;
  73290. x_step = 1;
  73291. x_end = header.width;
  73292. y_start = 0;
  73293. y_step = 1;
  73294. y_end = header.height;
  73295. break;
  73296. case TGATools._ORIGIN_BL:
  73297. x_start = 0;
  73298. x_step = 1;
  73299. x_end = header.width;
  73300. y_start = header.height - 1;
  73301. y_step = -1;
  73302. y_end = -1;
  73303. break;
  73304. case TGATools._ORIGIN_UR:
  73305. x_start = header.width - 1;
  73306. x_step = -1;
  73307. x_end = -1;
  73308. y_start = 0;
  73309. y_step = 1;
  73310. y_end = header.height;
  73311. break;
  73312. case TGATools._ORIGIN_BR:
  73313. x_start = header.width - 1;
  73314. x_step = -1;
  73315. x_end = -1;
  73316. y_start = header.height - 1;
  73317. y_step = -1;
  73318. y_end = -1;
  73319. break;
  73320. }
  73321. // Load the specify method
  73322. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  73323. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  73324. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  73325. };
  73326. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73327. var image = pixel_data, colormap = palettes;
  73328. var width = header.width, height = header.height;
  73329. var color, i = 0, x, y;
  73330. var imageData = new Uint8Array(width * height * 4);
  73331. for (y = y_start; y !== y_end; y += y_step) {
  73332. for (x = x_start; x !== x_end; x += x_step, i++) {
  73333. color = image[i];
  73334. imageData[(x + width * y) * 4 + 3] = 255;
  73335. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  73336. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  73337. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  73338. }
  73339. }
  73340. return imageData;
  73341. };
  73342. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73343. var image = pixel_data;
  73344. var width = header.width, height = header.height;
  73345. var color, i = 0, x, y;
  73346. var imageData = new Uint8Array(width * height * 4);
  73347. for (y = y_start; y !== y_end; y += y_step) {
  73348. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73349. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  73350. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  73351. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  73352. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  73353. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  73354. }
  73355. }
  73356. return imageData;
  73357. };
  73358. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73359. var image = pixel_data;
  73360. var width = header.width, height = header.height;
  73361. var i = 0, x, y;
  73362. var imageData = new Uint8Array(width * height * 4);
  73363. for (y = y_start; y !== y_end; y += y_step) {
  73364. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  73365. imageData[(x + width * y) * 4 + 3] = 255;
  73366. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73367. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73368. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73369. }
  73370. }
  73371. return imageData;
  73372. };
  73373. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73374. var image = pixel_data;
  73375. var width = header.width, height = header.height;
  73376. var i = 0, x, y;
  73377. var imageData = new Uint8Array(width * height * 4);
  73378. for (y = y_start; y !== y_end; y += y_step) {
  73379. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  73380. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73381. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73382. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73383. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  73384. }
  73385. }
  73386. return imageData;
  73387. };
  73388. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73389. var image = pixel_data;
  73390. var width = header.width, height = header.height;
  73391. var color, i = 0, x, y;
  73392. var imageData = new Uint8Array(width * height * 4);
  73393. for (y = y_start; y !== y_end; y += y_step) {
  73394. for (x = x_start; x !== x_end; x += x_step, i++) {
  73395. color = image[i];
  73396. imageData[(x + width * y) * 4 + 0] = color;
  73397. imageData[(x + width * y) * 4 + 1] = color;
  73398. imageData[(x + width * y) * 4 + 2] = color;
  73399. imageData[(x + width * y) * 4 + 3] = 255;
  73400. }
  73401. }
  73402. return imageData;
  73403. };
  73404. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73405. var image = pixel_data;
  73406. var width = header.width, height = header.height;
  73407. var i = 0, x, y;
  73408. var imageData = new Uint8Array(width * height * 4);
  73409. for (y = y_start; y !== y_end; y += y_step) {
  73410. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73411. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  73412. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  73413. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73414. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  73415. }
  73416. }
  73417. return imageData;
  73418. };
  73419. //private static _TYPE_NO_DATA = 0;
  73420. TGATools._TYPE_INDEXED = 1;
  73421. TGATools._TYPE_RGB = 2;
  73422. TGATools._TYPE_GREY = 3;
  73423. TGATools._TYPE_RLE_INDEXED = 9;
  73424. TGATools._TYPE_RLE_RGB = 10;
  73425. TGATools._TYPE_RLE_GREY = 11;
  73426. TGATools._ORIGIN_MASK = 0x30;
  73427. TGATools._ORIGIN_SHIFT = 0x04;
  73428. TGATools._ORIGIN_BL = 0x00;
  73429. TGATools._ORIGIN_BR = 0x01;
  73430. TGATools._ORIGIN_UL = 0x02;
  73431. TGATools._ORIGIN_UR = 0x03;
  73432. return TGATools;
  73433. }());
  73434. BABYLON.TGATools = TGATools;
  73435. })(BABYLON || (BABYLON = {}));
  73436. //# sourceMappingURL=babylon.tga.js.map
  73437. var BABYLON;
  73438. (function (BABYLON) {
  73439. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  73440. // All values and structures referenced from:
  73441. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  73442. var DDS_MAGIC = 0x20534444;
  73443. var
  73444. //DDSD_CAPS = 0x1,
  73445. //DDSD_HEIGHT = 0x2,
  73446. //DDSD_WIDTH = 0x4,
  73447. //DDSD_PITCH = 0x8,
  73448. //DDSD_PIXELFORMAT = 0x1000,
  73449. DDSD_MIPMAPCOUNT = 0x20000;
  73450. //DDSD_LINEARSIZE = 0x80000,
  73451. //DDSD_DEPTH = 0x800000;
  73452. // var DDSCAPS_COMPLEX = 0x8,
  73453. // DDSCAPS_MIPMAP = 0x400000,
  73454. // DDSCAPS_TEXTURE = 0x1000;
  73455. var DDSCAPS2_CUBEMAP = 0x200;
  73456. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  73457. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  73458. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  73459. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  73460. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  73461. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  73462. // DDSCAPS2_VOLUME = 0x200000;
  73463. var
  73464. //DDPF_ALPHAPIXELS = 0x1,
  73465. //DDPF_ALPHA = 0x2,
  73466. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  73467. //DDPF_YUV = 0x200,
  73468. DDPF_LUMINANCE = 0x20000;
  73469. function FourCCToInt32(value) {
  73470. return value.charCodeAt(0) +
  73471. (value.charCodeAt(1) << 8) +
  73472. (value.charCodeAt(2) << 16) +
  73473. (value.charCodeAt(3) << 24);
  73474. }
  73475. function Int32ToFourCC(value) {
  73476. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  73477. }
  73478. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  73479. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  73480. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  73481. var FOURCC_DX10 = FourCCToInt32("DX10");
  73482. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  73483. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  73484. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  73485. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  73486. var headerLengthInt = 31; // The header length in 32 bit ints
  73487. // Offsets into the header array
  73488. var off_magic = 0;
  73489. var off_size = 1;
  73490. var off_flags = 2;
  73491. var off_height = 3;
  73492. var off_width = 4;
  73493. var off_mipmapCount = 7;
  73494. var off_pfFlags = 20;
  73495. var off_pfFourCC = 21;
  73496. var off_RGBbpp = 22;
  73497. var off_RMask = 23;
  73498. var off_GMask = 24;
  73499. var off_BMask = 25;
  73500. var off_AMask = 26;
  73501. // var off_caps1 = 27;
  73502. var off_caps2 = 28;
  73503. // var off_caps3 = 29;
  73504. // var off_caps4 = 30;
  73505. var off_dxgiFormat = 32;
  73506. ;
  73507. var DDSTools = /** @class */ (function () {
  73508. function DDSTools() {
  73509. }
  73510. DDSTools.GetDDSInfo = function (arrayBuffer) {
  73511. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73512. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  73513. var mipmapCount = 1;
  73514. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  73515. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73516. }
  73517. var fourCC = header[off_pfFourCC];
  73518. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  73519. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73520. switch (fourCC) {
  73521. case FOURCC_D3DFMT_R16G16B16A16F:
  73522. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73523. break;
  73524. case FOURCC_D3DFMT_R32G32B32A32F:
  73525. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73526. break;
  73527. case FOURCC_DX10:
  73528. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  73529. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73530. break;
  73531. }
  73532. }
  73533. return {
  73534. width: header[off_width],
  73535. height: header[off_height],
  73536. mipmapCount: mipmapCount,
  73537. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  73538. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  73539. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  73540. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  73541. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  73542. dxgiFormat: dxgiFormat,
  73543. textureType: textureType
  73544. };
  73545. };
  73546. DDSTools._ToHalfFloat = function (value) {
  73547. if (!DDSTools._FloatView) {
  73548. DDSTools._FloatView = new Float32Array(1);
  73549. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  73550. }
  73551. DDSTools._FloatView[0] = value;
  73552. var x = DDSTools._Int32View[0];
  73553. var bits = (x >> 16) & 0x8000; /* Get the sign */
  73554. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  73555. var e = (x >> 23) & 0xff; /* Using int is faster here */
  73556. /* If zero, or denormal, or exponent underflows too much for a denormal
  73557. * half, return signed zero. */
  73558. if (e < 103) {
  73559. return bits;
  73560. }
  73561. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  73562. if (e > 142) {
  73563. bits |= 0x7c00;
  73564. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  73565. * not Inf, so make sure we set one mantissa bit too. */
  73566. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  73567. return bits;
  73568. }
  73569. /* If exponent underflows but not too much, return a denormal */
  73570. if (e < 113) {
  73571. m |= 0x0800;
  73572. /* Extra rounding may overflow and set mantissa to 0 and exponent
  73573. * to 1, which is OK. */
  73574. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  73575. return bits;
  73576. }
  73577. bits |= ((e - 112) << 10) | (m >> 1);
  73578. bits += m & 1;
  73579. return bits;
  73580. };
  73581. DDSTools._FromHalfFloat = function (value) {
  73582. var s = (value & 0x8000) >> 15;
  73583. var e = (value & 0x7C00) >> 10;
  73584. var f = value & 0x03FF;
  73585. if (e === 0) {
  73586. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  73587. }
  73588. else if (e == 0x1F) {
  73589. return f ? NaN : ((s ? -1 : 1) * Infinity);
  73590. }
  73591. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  73592. };
  73593. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73594. var destArray = new Float32Array(dataLength);
  73595. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73596. var index = 0;
  73597. for (var y = 0; y < height; y++) {
  73598. for (var x = 0; x < width; x++) {
  73599. var srcPos = (x + y * width) * 4;
  73600. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  73601. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  73602. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  73603. if (DDSTools.StoreLODInAlphaChannel) {
  73604. destArray[index + 3] = lod;
  73605. }
  73606. else {
  73607. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  73608. }
  73609. index += 4;
  73610. }
  73611. }
  73612. return destArray;
  73613. };
  73614. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73615. if (DDSTools.StoreLODInAlphaChannel) {
  73616. var destArray = new Uint16Array(dataLength);
  73617. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73618. var index = 0;
  73619. for (var y = 0; y < height; y++) {
  73620. for (var x = 0; x < width; x++) {
  73621. var srcPos = (x + y * width) * 4;
  73622. destArray[index] = srcData[srcPos];
  73623. destArray[index + 1] = srcData[srcPos + 1];
  73624. destArray[index + 2] = srcData[srcPos + 2];
  73625. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  73626. index += 4;
  73627. }
  73628. }
  73629. return destArray;
  73630. }
  73631. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  73632. };
  73633. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73634. if (DDSTools.StoreLODInAlphaChannel) {
  73635. var destArray = new Float32Array(dataLength);
  73636. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73637. var index = 0;
  73638. for (var y = 0; y < height; y++) {
  73639. for (var x = 0; x < width; x++) {
  73640. var srcPos = (x + y * width) * 4;
  73641. destArray[index] = srcData[srcPos];
  73642. destArray[index + 1] = srcData[srcPos + 1];
  73643. destArray[index + 2] = srcData[srcPos + 2];
  73644. destArray[index + 3] = lod;
  73645. index += 4;
  73646. }
  73647. }
  73648. return destArray;
  73649. }
  73650. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  73651. };
  73652. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73653. var destArray = new Uint8Array(dataLength);
  73654. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73655. var index = 0;
  73656. for (var y = 0; y < height; y++) {
  73657. for (var x = 0; x < width; x++) {
  73658. var srcPos = (x + y * width) * 4;
  73659. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  73660. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  73661. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  73662. if (DDSTools.StoreLODInAlphaChannel) {
  73663. destArray[index + 3] = lod;
  73664. }
  73665. else {
  73666. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  73667. }
  73668. index += 4;
  73669. }
  73670. }
  73671. return destArray;
  73672. };
  73673. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73674. var destArray = new Uint8Array(dataLength);
  73675. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73676. var index = 0;
  73677. for (var y = 0; y < height; y++) {
  73678. for (var x = 0; x < width; x++) {
  73679. var srcPos = (x + y * width) * 4;
  73680. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  73681. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  73682. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  73683. if (DDSTools.StoreLODInAlphaChannel) {
  73684. destArray[index + 3] = lod;
  73685. }
  73686. else {
  73687. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  73688. }
  73689. index += 4;
  73690. }
  73691. }
  73692. return destArray;
  73693. };
  73694. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  73695. var byteArray = new Uint8Array(dataLength);
  73696. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73697. var index = 0;
  73698. for (var y = 0; y < height; y++) {
  73699. for (var x = 0; x < width; x++) {
  73700. var srcPos = (x + y * width) * 4;
  73701. byteArray[index] = srcData[srcPos + rOffset];
  73702. byteArray[index + 1] = srcData[srcPos + gOffset];
  73703. byteArray[index + 2] = srcData[srcPos + bOffset];
  73704. byteArray[index + 3] = srcData[srcPos + aOffset];
  73705. index += 4;
  73706. }
  73707. }
  73708. return byteArray;
  73709. };
  73710. DDSTools._ExtractLongWordOrder = function (value) {
  73711. if (value === 0 || value === 255 || value === -16777216) {
  73712. return 0;
  73713. }
  73714. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  73715. };
  73716. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  73717. var byteArray = new Uint8Array(dataLength);
  73718. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73719. var index = 0;
  73720. for (var y = 0; y < height; y++) {
  73721. for (var x = 0; x < width; x++) {
  73722. var srcPos = (x + y * width) * 3;
  73723. byteArray[index] = srcData[srcPos + rOffset];
  73724. byteArray[index + 1] = srcData[srcPos + gOffset];
  73725. byteArray[index + 2] = srcData[srcPos + bOffset];
  73726. index += 3;
  73727. }
  73728. }
  73729. return byteArray;
  73730. };
  73731. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  73732. var byteArray = new Uint8Array(dataLength);
  73733. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73734. var index = 0;
  73735. for (var y = 0; y < height; y++) {
  73736. for (var x = 0; x < width; x++) {
  73737. var srcPos = (x + y * width);
  73738. byteArray[index] = srcData[srcPos];
  73739. index++;
  73740. }
  73741. }
  73742. return byteArray;
  73743. };
  73744. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  73745. if (lodIndex === void 0) { lodIndex = -1; }
  73746. var ext = engine.getCaps().s3tc;
  73747. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73748. var fourCC, width, height, dataLength = 0, dataOffset;
  73749. var byteArray, mipmapCount, mip;
  73750. var internalFormat = 0;
  73751. var format = 0;
  73752. var blockBytes = 1;
  73753. if (header[off_magic] !== DDS_MAGIC) {
  73754. BABYLON.Tools.Error("Invalid magic number in DDS header");
  73755. return;
  73756. }
  73757. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  73758. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  73759. return;
  73760. }
  73761. if (info.isCompressed && !ext) {
  73762. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  73763. return;
  73764. }
  73765. var bpp = header[off_RGBbpp];
  73766. dataOffset = header[off_size] + 4;
  73767. var computeFormats = false;
  73768. if (info.isFourCC) {
  73769. fourCC = header[off_pfFourCC];
  73770. switch (fourCC) {
  73771. case FOURCC_DXT1:
  73772. blockBytes = 8;
  73773. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  73774. break;
  73775. case FOURCC_DXT3:
  73776. blockBytes = 16;
  73777. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  73778. break;
  73779. case FOURCC_DXT5:
  73780. blockBytes = 16;
  73781. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  73782. break;
  73783. case FOURCC_D3DFMT_R16G16B16A16F:
  73784. computeFormats = true;
  73785. break;
  73786. case FOURCC_D3DFMT_R32G32B32A32F:
  73787. computeFormats = true;
  73788. break;
  73789. case FOURCC_DX10:
  73790. // There is an additionnal header so dataOffset need to be changed
  73791. dataOffset += 5 * 4; // 5 uints
  73792. var supported = false;
  73793. switch (info.dxgiFormat) {
  73794. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  73795. computeFormats = true;
  73796. supported = true;
  73797. break;
  73798. case DXGI_FORMAT_B8G8R8X8_UNORM:
  73799. info.isRGB = true;
  73800. info.isFourCC = false;
  73801. bpp = 32;
  73802. supported = true;
  73803. break;
  73804. }
  73805. if (supported) {
  73806. break;
  73807. }
  73808. default:
  73809. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  73810. return;
  73811. }
  73812. }
  73813. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  73814. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  73815. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  73816. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  73817. if (computeFormats) {
  73818. format = engine._getWebGLTextureType(info.textureType);
  73819. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73820. }
  73821. mipmapCount = 1;
  73822. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  73823. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73824. }
  73825. for (var face = 0; face < faces; face++) {
  73826. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  73827. width = header[off_width];
  73828. height = header[off_height];
  73829. for (mip = 0; mip < mipmapCount; ++mip) {
  73830. if (lodIndex === -1 || lodIndex === mip) {
  73831. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  73832. var i = (lodIndex === -1) ? mip : 0;
  73833. if (!info.isCompressed && info.isFourCC) {
  73834. dataLength = width * height * 4;
  73835. var floatArray = null;
  73836. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  73837. if (bpp === 128) {
  73838. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73839. }
  73840. else if (bpp === 64) {
  73841. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73842. }
  73843. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73844. format = engine._getWebGLTextureType(info.textureType);
  73845. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73846. }
  73847. else {
  73848. if (bpp === 128) {
  73849. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73850. }
  73851. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  73852. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73853. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73854. format = engine._getWebGLTextureType(info.textureType);
  73855. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73856. }
  73857. else {
  73858. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73859. }
  73860. }
  73861. if (floatArray) {
  73862. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  73863. }
  73864. }
  73865. else if (info.isRGB) {
  73866. if (bpp === 24) {
  73867. dataLength = width * height * 3;
  73868. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  73869. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  73870. }
  73871. else {
  73872. dataLength = width * height * 4;
  73873. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  73874. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  73875. }
  73876. }
  73877. else if (info.isLuminance) {
  73878. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  73879. var unpaddedRowSize = width;
  73880. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  73881. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  73882. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  73883. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  73884. }
  73885. else {
  73886. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  73887. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  73888. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  73889. }
  73890. }
  73891. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  73892. width *= 0.5;
  73893. height *= 0.5;
  73894. width = Math.max(1.0, width);
  73895. height = Math.max(1.0, height);
  73896. }
  73897. if (currentFace !== undefined) {
  73898. // Loading a single face
  73899. break;
  73900. }
  73901. }
  73902. };
  73903. DDSTools.StoreLODInAlphaChannel = false;
  73904. return DDSTools;
  73905. }());
  73906. BABYLON.DDSTools = DDSTools;
  73907. })(BABYLON || (BABYLON = {}));
  73908. //# sourceMappingURL=babylon.dds.js.map
  73909. var BABYLON;
  73910. (function (BABYLON) {
  73911. /**
  73912. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  73913. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  73914. */
  73915. var KhronosTextureContainer = /** @class */ (function () {
  73916. /**
  73917. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  73918. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  73919. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  73920. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  73921. */
  73922. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  73923. this.arrayBuffer = arrayBuffer;
  73924. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  73925. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  73926. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  73927. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  73928. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  73929. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  73930. BABYLON.Tools.Error("texture missing KTX identifier");
  73931. return;
  73932. }
  73933. // load the reset of the header in native 32 bit int
  73934. var header = new Int32Array(this.arrayBuffer, 12, 13);
  73935. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  73936. var oppositeEndianess = header[0] === 0x01020304;
  73937. // read all the header elements in order they exist in the file, without modification (sans endainness)
  73938. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  73939. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  73940. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  73941. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  73942. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  73943. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  73944. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  73945. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  73946. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  73947. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  73948. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  73949. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  73950. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  73951. if (this.glType !== 0) {
  73952. BABYLON.Tools.Error("only compressed formats currently supported");
  73953. return;
  73954. }
  73955. else {
  73956. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  73957. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  73958. }
  73959. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  73960. BABYLON.Tools.Error("only 2D textures currently supported");
  73961. return;
  73962. }
  73963. if (this.numberOfArrayElements !== 0) {
  73964. BABYLON.Tools.Error("texture arrays not currently supported");
  73965. return;
  73966. }
  73967. if (this.numberOfFaces !== facesExpected) {
  73968. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  73969. return;
  73970. }
  73971. // we now have a completely validated file, so could use existence of loadType as success
  73972. // would need to make this more elaborate & adjust checks above to support more than one load type
  73973. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  73974. }
  73975. // not as fast hardware based, but will probably never need to use
  73976. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  73977. return ((val & 0xFF) << 24)
  73978. | ((val & 0xFF00) << 8)
  73979. | ((val >> 8) & 0xFF00)
  73980. | ((val >> 24) & 0xFF);
  73981. };
  73982. /**
  73983. * It is assumed that the texture has already been created & is currently bound
  73984. */
  73985. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  73986. switch (this.loadType) {
  73987. case KhronosTextureContainer.COMPRESSED_2D:
  73988. this._upload2DCompressedLevels(gl, loadMipmaps);
  73989. break;
  73990. case KhronosTextureContainer.TEX_2D:
  73991. case KhronosTextureContainer.COMPRESSED_3D:
  73992. case KhronosTextureContainer.TEX_3D:
  73993. }
  73994. };
  73995. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  73996. // initialize width & height for level 1
  73997. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  73998. var width = this.pixelWidth;
  73999. var height = this.pixelHeight;
  74000. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  74001. for (var level = 0; level < mipmapCount; level++) {
  74002. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  74003. for (var face = 0; face < this.numberOfFaces; face++) {
  74004. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  74005. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  74006. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  74007. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  74008. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  74009. }
  74010. width = Math.max(1.0, width * 0.5);
  74011. height = Math.max(1.0, height * 0.5);
  74012. }
  74013. };
  74014. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  74015. // load types
  74016. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  74017. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  74018. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  74019. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  74020. return KhronosTextureContainer;
  74021. }());
  74022. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  74023. })(BABYLON || (BABYLON = {}));
  74024. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  74025. var BABYLON;
  74026. (function (BABYLON) {
  74027. var Debug = /** @class */ (function () {
  74028. function Debug() {
  74029. }
  74030. Debug.AxesViewer = /** @class */ (function () {
  74031. function AxesViewer(scene, scaleLines) {
  74032. if (scaleLines === void 0) { scaleLines = 1; }
  74033. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74034. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74035. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74036. this.scaleLines = 1;
  74037. this.scaleLines = scaleLines;
  74038. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  74039. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  74040. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  74041. this._xmesh.renderingGroupId = 2;
  74042. this._ymesh.renderingGroupId = 2;
  74043. this._zmesh.renderingGroupId = 2;
  74044. this._xmesh.material.checkReadyOnlyOnce = true;
  74045. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  74046. this._ymesh.material.checkReadyOnlyOnce = true;
  74047. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  74048. this._zmesh.material.checkReadyOnlyOnce = true;
  74049. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  74050. this.scene = scene;
  74051. }
  74052. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  74053. var scaleLines = this.scaleLines;
  74054. if (this._xmesh) {
  74055. this._xmesh.position.copyFrom(position);
  74056. }
  74057. if (this._ymesh) {
  74058. this._ymesh.position.copyFrom(position);
  74059. }
  74060. if (this._zmesh) {
  74061. this._zmesh.position.copyFrom(position);
  74062. }
  74063. var point2 = this._xline[1];
  74064. point2.x = xaxis.x * scaleLines;
  74065. point2.y = xaxis.y * scaleLines;
  74066. point2.z = xaxis.z * scaleLines;
  74067. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  74068. point2 = this._yline[1];
  74069. point2.x = yaxis.x * scaleLines;
  74070. point2.y = yaxis.y * scaleLines;
  74071. point2.z = yaxis.z * scaleLines;
  74072. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  74073. point2 = this._zline[1];
  74074. point2.x = zaxis.x * scaleLines;
  74075. point2.y = zaxis.y * scaleLines;
  74076. point2.z = zaxis.z * scaleLines;
  74077. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  74078. };
  74079. AxesViewer.prototype.dispose = function () {
  74080. if (this._xmesh) {
  74081. this._xmesh.dispose();
  74082. }
  74083. if (this._ymesh) {
  74084. this._ymesh.dispose();
  74085. }
  74086. if (this._zmesh) {
  74087. this._zmesh.dispose();
  74088. }
  74089. this._xmesh = null;
  74090. this._ymesh = null;
  74091. this._zmesh = null;
  74092. this.scene = null;
  74093. };
  74094. return AxesViewer;
  74095. }());
  74096. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  74097. __extends(BoneAxesViewer, _super);
  74098. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  74099. if (scaleLines === void 0) { scaleLines = 1; }
  74100. var _this = _super.call(this, scene, scaleLines) || this;
  74101. _this.pos = BABYLON.Vector3.Zero();
  74102. _this.xaxis = BABYLON.Vector3.Zero();
  74103. _this.yaxis = BABYLON.Vector3.Zero();
  74104. _this.zaxis = BABYLON.Vector3.Zero();
  74105. _this.mesh = mesh;
  74106. _this.bone = bone;
  74107. return _this;
  74108. }
  74109. BoneAxesViewer.prototype.update = function () {
  74110. if (!this.mesh || !this.bone) {
  74111. return;
  74112. }
  74113. var bone = this.bone;
  74114. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  74115. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  74116. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  74117. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  74118. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  74119. };
  74120. BoneAxesViewer.prototype.dispose = function () {
  74121. if (this.mesh) {
  74122. this.mesh = null;
  74123. this.bone = null;
  74124. _super.prototype.dispose.call(this);
  74125. }
  74126. };
  74127. return BoneAxesViewer;
  74128. }(Debug.AxesViewer));
  74129. Debug.PhysicsViewer = /** @class */ (function () {
  74130. function PhysicsViewer(scene) {
  74131. this._impostors = [];
  74132. this._meshes = [];
  74133. this._numMeshes = 0;
  74134. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74135. var physicEngine = this._scene.getPhysicsEngine();
  74136. if (physicEngine) {
  74137. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  74138. }
  74139. }
  74140. PhysicsViewer.prototype._updateDebugMeshes = function () {
  74141. var plugin = this._physicsEnginePlugin;
  74142. for (var i = 0; i < this._numMeshes; i++) {
  74143. var impostor = this._impostors[i];
  74144. if (!impostor) {
  74145. continue;
  74146. }
  74147. if (impostor.isDisposed) {
  74148. this.hideImpostor(this._impostors[i--]);
  74149. }
  74150. else {
  74151. var mesh = this._meshes[i];
  74152. if (mesh && plugin) {
  74153. plugin.syncMeshWithImpostor(mesh, impostor);
  74154. }
  74155. }
  74156. }
  74157. };
  74158. PhysicsViewer.prototype.showImpostor = function (impostor) {
  74159. if (!this._scene) {
  74160. return;
  74161. }
  74162. for (var i = 0; i < this._numMeshes; i++) {
  74163. if (this._impostors[i] == impostor) {
  74164. return;
  74165. }
  74166. }
  74167. var debugMesh = this._getDebugMesh(impostor, this._scene);
  74168. if (debugMesh) {
  74169. this._impostors[this._numMeshes] = impostor;
  74170. this._meshes[this._numMeshes] = debugMesh;
  74171. if (this._numMeshes === 0) {
  74172. this._renderFunction = this._updateDebugMeshes.bind(this);
  74173. this._scene.registerBeforeRender(this._renderFunction);
  74174. }
  74175. this._numMeshes++;
  74176. }
  74177. };
  74178. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  74179. if (!impostor || !this._scene) {
  74180. return;
  74181. }
  74182. var removed = false;
  74183. for (var i = 0; i < this._numMeshes; i++) {
  74184. if (this._impostors[i] == impostor) {
  74185. var mesh = this._meshes[i];
  74186. if (!mesh) {
  74187. continue;
  74188. }
  74189. this._scene.removeMesh(mesh);
  74190. mesh.dispose();
  74191. this._numMeshes--;
  74192. if (this._numMeshes > 0) {
  74193. this._meshes[i] = this._meshes[this._numMeshes];
  74194. this._impostors[i] = this._impostors[this._numMeshes];
  74195. this._meshes[this._numMeshes] = null;
  74196. this._impostors[this._numMeshes] = null;
  74197. }
  74198. else {
  74199. this._meshes[0] = null;
  74200. this._impostors[0] = null;
  74201. }
  74202. removed = true;
  74203. break;
  74204. }
  74205. }
  74206. if (removed && this._numMeshes === 0) {
  74207. this._scene.unregisterBeforeRender(this._renderFunction);
  74208. }
  74209. };
  74210. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  74211. if (!this._debugMaterial) {
  74212. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  74213. this._debugMaterial.wireframe = true;
  74214. }
  74215. return this._debugMaterial;
  74216. };
  74217. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  74218. if (!this._debugBoxMesh) {
  74219. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  74220. this._debugBoxMesh.renderingGroupId = 1;
  74221. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74222. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  74223. scene.removeMesh(this._debugBoxMesh);
  74224. }
  74225. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  74226. };
  74227. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  74228. if (!this._debugSphereMesh) {
  74229. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  74230. this._debugSphereMesh.renderingGroupId = 1;
  74231. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74232. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  74233. scene.removeMesh(this._debugSphereMesh);
  74234. }
  74235. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  74236. };
  74237. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  74238. var mesh = null;
  74239. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  74240. mesh = this._getDebugBoxMesh(scene);
  74241. impostor.getBoxSizeToRef(mesh.scaling);
  74242. }
  74243. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  74244. mesh = this._getDebugSphereMesh(scene);
  74245. var radius = impostor.getRadius();
  74246. mesh.scaling.x = radius * 2;
  74247. mesh.scaling.y = radius * 2;
  74248. mesh.scaling.z = radius * 2;
  74249. }
  74250. return mesh;
  74251. };
  74252. PhysicsViewer.prototype.dispose = function () {
  74253. for (var i = 0; i < this._numMeshes; i++) {
  74254. this.hideImpostor(this._impostors[i]);
  74255. }
  74256. if (this._debugBoxMesh) {
  74257. this._debugBoxMesh.dispose();
  74258. }
  74259. if (this._debugSphereMesh) {
  74260. this._debugSphereMesh.dispose();
  74261. }
  74262. if (this._debugMaterial) {
  74263. this._debugMaterial.dispose();
  74264. }
  74265. this._impostors.length = 0;
  74266. this._scene = null;
  74267. this._physicsEnginePlugin = null;
  74268. };
  74269. return PhysicsViewer;
  74270. }());
  74271. Debug.SkeletonViewer = /** @class */ (function () {
  74272. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  74273. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  74274. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  74275. this.skeleton = skeleton;
  74276. this.mesh = mesh;
  74277. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  74278. this.renderingGroupId = renderingGroupId;
  74279. this.color = BABYLON.Color3.White();
  74280. this._debugLines = new Array();
  74281. this._isEnabled = false;
  74282. this._scene = scene;
  74283. this.update();
  74284. this._renderFunction = this.update.bind(this);
  74285. }
  74286. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  74287. get: function () {
  74288. return this._isEnabled;
  74289. },
  74290. set: function (value) {
  74291. if (this._isEnabled === value) {
  74292. return;
  74293. }
  74294. this._isEnabled = value;
  74295. if (value) {
  74296. this._scene.registerBeforeRender(this._renderFunction);
  74297. }
  74298. else {
  74299. this._scene.unregisterBeforeRender(this._renderFunction);
  74300. }
  74301. },
  74302. enumerable: true,
  74303. configurable: true
  74304. });
  74305. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  74306. if (x === void 0) { x = 0; }
  74307. if (y === void 0) { y = 0; }
  74308. if (z === void 0) { z = 0; }
  74309. var tmat = BABYLON.Tmp.Matrix[0];
  74310. var parentBone = bone.getParent();
  74311. tmat.copyFrom(bone.getLocalMatrix());
  74312. if (x !== 0 || y !== 0 || z !== 0) {
  74313. var tmat2 = BABYLON.Tmp.Matrix[1];
  74314. BABYLON.Matrix.IdentityToRef(tmat2);
  74315. tmat2.m[12] = x;
  74316. tmat2.m[13] = y;
  74317. tmat2.m[14] = z;
  74318. tmat2.multiplyToRef(tmat, tmat);
  74319. }
  74320. if (parentBone) {
  74321. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  74322. }
  74323. tmat.multiplyToRef(meshMat, tmat);
  74324. position.x = tmat.m[12];
  74325. position.y = tmat.m[13];
  74326. position.z = tmat.m[14];
  74327. };
  74328. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  74329. var len = bones.length;
  74330. var meshPos = this.mesh.position;
  74331. for (var i = 0; i < len; i++) {
  74332. var bone = bones[i];
  74333. var points = this._debugLines[i];
  74334. if (!points) {
  74335. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74336. this._debugLines[i] = points;
  74337. }
  74338. this._getBonePosition(points[0], bone, meshMat);
  74339. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  74340. points[0].subtractInPlace(meshPos);
  74341. points[1].subtractInPlace(meshPos);
  74342. }
  74343. };
  74344. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  74345. var len = bones.length;
  74346. var boneNum = 0;
  74347. var meshPos = this.mesh.position;
  74348. for (var i = len - 1; i >= 0; i--) {
  74349. var childBone = bones[i];
  74350. var parentBone = childBone.getParent();
  74351. if (!parentBone) {
  74352. continue;
  74353. }
  74354. var points = this._debugLines[boneNum];
  74355. if (!points) {
  74356. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74357. this._debugLines[boneNum] = points;
  74358. }
  74359. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  74360. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  74361. points[0].subtractInPlace(meshPos);
  74362. points[1].subtractInPlace(meshPos);
  74363. boneNum++;
  74364. }
  74365. };
  74366. SkeletonViewer.prototype.update = function () {
  74367. if (this.autoUpdateBonesMatrices) {
  74368. this.skeleton.computeAbsoluteTransforms();
  74369. }
  74370. if (this.skeleton.bones[0].length === undefined) {
  74371. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74372. }
  74373. else {
  74374. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74375. }
  74376. if (!this._debugMesh) {
  74377. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  74378. this._debugMesh.renderingGroupId = this.renderingGroupId;
  74379. }
  74380. else {
  74381. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  74382. }
  74383. this._debugMesh.position.copyFrom(this.mesh.position);
  74384. this._debugMesh.color = this.color;
  74385. };
  74386. SkeletonViewer.prototype.dispose = function () {
  74387. if (this._debugMesh) {
  74388. this.isEnabled = false;
  74389. this._debugMesh.dispose();
  74390. this._debugMesh = null;
  74391. }
  74392. };
  74393. return SkeletonViewer;
  74394. }());
  74395. return Debug;
  74396. }());
  74397. BABYLON.Debug = Debug;
  74398. })(BABYLON || (BABYLON = {}));
  74399. //# sourceMappingURL=babylon.debugModules.js.map
  74400. var BABYLON;
  74401. (function (BABYLON) {
  74402. var RayHelper = /** @class */ (function () {
  74403. function RayHelper(ray) {
  74404. this.ray = ray;
  74405. }
  74406. RayHelper.CreateAndShow = function (ray, scene, color) {
  74407. var helper = new RayHelper(ray);
  74408. helper.show(scene, color);
  74409. return helper;
  74410. };
  74411. RayHelper.prototype.show = function (scene, color) {
  74412. if (!this._renderFunction && this.ray) {
  74413. var ray = this.ray;
  74414. this._renderFunction = this._render.bind(this);
  74415. this._scene = scene;
  74416. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  74417. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  74418. if (this._renderFunction) {
  74419. this._scene.registerBeforeRender(this._renderFunction);
  74420. }
  74421. }
  74422. if (color && this._renderLine) {
  74423. this._renderLine.color.copyFrom(color);
  74424. }
  74425. };
  74426. RayHelper.prototype.hide = function () {
  74427. if (this._renderFunction && this._scene) {
  74428. this._scene.unregisterBeforeRender(this._renderFunction);
  74429. this._scene = null;
  74430. this._renderFunction = null;
  74431. if (this._renderLine) {
  74432. this._renderLine.dispose();
  74433. this._renderLine = null;
  74434. }
  74435. this._renderPoints = [];
  74436. }
  74437. };
  74438. RayHelper.prototype._render = function () {
  74439. var ray = this.ray;
  74440. if (!ray) {
  74441. return;
  74442. }
  74443. var point = this._renderPoints[1];
  74444. var len = Math.min(ray.length, 1000000);
  74445. point.copyFrom(ray.direction);
  74446. point.scaleInPlace(len);
  74447. point.addInPlace(ray.origin);
  74448. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  74449. };
  74450. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  74451. this._attachedToMesh = mesh;
  74452. var ray = this.ray;
  74453. if (!ray) {
  74454. return;
  74455. }
  74456. if (!ray.direction) {
  74457. ray.direction = BABYLON.Vector3.Zero();
  74458. }
  74459. if (!ray.origin) {
  74460. ray.origin = BABYLON.Vector3.Zero();
  74461. }
  74462. if (length) {
  74463. ray.length = length;
  74464. }
  74465. if (!meshSpaceOrigin) {
  74466. meshSpaceOrigin = BABYLON.Vector3.Zero();
  74467. }
  74468. if (!meshSpaceDirection) {
  74469. // -1 so that this will work with Mesh.lookAt
  74470. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  74471. }
  74472. if (!this._meshSpaceDirection) {
  74473. this._meshSpaceDirection = meshSpaceDirection.clone();
  74474. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  74475. }
  74476. else {
  74477. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  74478. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  74479. }
  74480. if (!this._updateToMeshFunction) {
  74481. this._updateToMeshFunction = this._updateToMesh.bind(this);
  74482. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  74483. }
  74484. this._updateToMesh();
  74485. };
  74486. RayHelper.prototype.detachFromMesh = function () {
  74487. if (this._attachedToMesh) {
  74488. if (this._updateToMeshFunction) {
  74489. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  74490. }
  74491. this._attachedToMesh = null;
  74492. this._updateToMeshFunction = null;
  74493. }
  74494. };
  74495. RayHelper.prototype._updateToMesh = function () {
  74496. var ray = this.ray;
  74497. if (!this._attachedToMesh || !ray) {
  74498. return;
  74499. }
  74500. if (this._attachedToMesh._isDisposed) {
  74501. this.detachFromMesh();
  74502. return;
  74503. }
  74504. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  74505. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  74506. };
  74507. RayHelper.prototype.dispose = function () {
  74508. this.hide();
  74509. this.detachFromMesh();
  74510. this.ray = null;
  74511. };
  74512. return RayHelper;
  74513. }());
  74514. BABYLON.RayHelper = RayHelper;
  74515. })(BABYLON || (BABYLON = {}));
  74516. //# sourceMappingURL=babylon.rayHelper.js.map
  74517. var BABYLON;
  74518. (function (BABYLON) {
  74519. // load the inspector using require, if not present in the global namespace.
  74520. var DebugLayer = /** @class */ (function () {
  74521. function DebugLayer(scene) {
  74522. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74523. this._scene = scene;
  74524. // load inspector using require, if it doesn't exist on the global namespace.
  74525. }
  74526. /** Creates the inspector window. */
  74527. DebugLayer.prototype._createInspector = function (config) {
  74528. if (config === void 0) { config = {}; }
  74529. var popup = config.popup || false;
  74530. var initialTab = config.initialTab || 0;
  74531. var parentElement = config.parentElement || null;
  74532. if (!this._inspector) {
  74533. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74534. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  74535. } // else nothing to do,; instance is already existing
  74536. };
  74537. DebugLayer.prototype.isVisible = function () {
  74538. if (!this._inspector) {
  74539. return false;
  74540. }
  74541. return true;
  74542. };
  74543. DebugLayer.prototype.hide = function () {
  74544. if (this._inspector) {
  74545. try {
  74546. this._inspector.dispose();
  74547. }
  74548. catch (e) {
  74549. // If the inspector has been removed directly from the inspector tool
  74550. }
  74551. this._inspector = null;
  74552. }
  74553. };
  74554. DebugLayer.prototype.show = function (config) {
  74555. if (config === void 0) { config = {}; }
  74556. if (typeof this.BJSINSPECTOR == 'undefined') {
  74557. // Load inspector and add it to the DOM
  74558. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  74559. }
  74560. else {
  74561. // Otherwise creates the inspector
  74562. this._createInspector(config);
  74563. }
  74564. };
  74565. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  74566. return DebugLayer;
  74567. }());
  74568. BABYLON.DebugLayer = DebugLayer;
  74569. })(BABYLON || (BABYLON = {}));
  74570. //# sourceMappingURL=babylon.debugLayer.js.map
  74571. var BABYLON;
  74572. (function (BABYLON) {
  74573. var BoundingBoxRenderer = /** @class */ (function () {
  74574. function BoundingBoxRenderer(scene) {
  74575. this.frontColor = new BABYLON.Color3(1, 1, 1);
  74576. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  74577. this.showBackLines = true;
  74578. this.renderList = new BABYLON.SmartArray(32);
  74579. this._vertexBuffers = {};
  74580. this._scene = scene;
  74581. }
  74582. BoundingBoxRenderer.prototype._prepareRessources = function () {
  74583. if (this._colorShader) {
  74584. return;
  74585. }
  74586. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  74587. attributes: [BABYLON.VertexBuffer.PositionKind],
  74588. uniforms: ["world", "viewProjection", "color"]
  74589. });
  74590. var engine = this._scene.getEngine();
  74591. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  74592. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  74593. this._createIndexBuffer();
  74594. };
  74595. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  74596. var engine = this._scene.getEngine();
  74597. 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]);
  74598. };
  74599. BoundingBoxRenderer.prototype._rebuild = function () {
  74600. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74601. if (vb) {
  74602. vb._rebuild();
  74603. }
  74604. this._createIndexBuffer();
  74605. };
  74606. BoundingBoxRenderer.prototype.reset = function () {
  74607. this.renderList.reset();
  74608. };
  74609. BoundingBoxRenderer.prototype.render = function () {
  74610. if (this.renderList.length === 0) {
  74611. return;
  74612. }
  74613. this._prepareRessources();
  74614. if (!this._colorShader.isReady()) {
  74615. return;
  74616. }
  74617. var engine = this._scene.getEngine();
  74618. engine.setDepthWrite(false);
  74619. this._colorShader._preBind();
  74620. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  74621. var boundingBox = this.renderList.data[boundingBoxIndex];
  74622. var min = boundingBox.minimum;
  74623. var max = boundingBox.maximum;
  74624. var diff = max.subtract(min);
  74625. var median = min.add(diff.scale(0.5));
  74626. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74627. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74628. .multiply(boundingBox.getWorldMatrix());
  74629. // VBOs
  74630. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74631. if (this.showBackLines) {
  74632. // Back
  74633. engine.setDepthFunctionToGreaterOrEqual();
  74634. this._scene.resetCachedMaterial();
  74635. this._colorShader.setColor4("color", this.backColor.toColor4());
  74636. this._colorShader.bind(worldMatrix);
  74637. // Draw order
  74638. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74639. }
  74640. // Front
  74641. engine.setDepthFunctionToLess();
  74642. this._scene.resetCachedMaterial();
  74643. this._colorShader.setColor4("color", this.frontColor.toColor4());
  74644. this._colorShader.bind(worldMatrix);
  74645. // Draw order
  74646. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74647. }
  74648. this._colorShader.unbind();
  74649. engine.setDepthFunctionToLessOrEqual();
  74650. engine.setDepthWrite(true);
  74651. };
  74652. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  74653. this._prepareRessources();
  74654. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  74655. return;
  74656. }
  74657. var engine = this._scene.getEngine();
  74658. engine.setDepthWrite(false);
  74659. engine.setColorWrite(false);
  74660. this._colorShader._preBind();
  74661. var boundingBox = mesh._boundingInfo.boundingBox;
  74662. var min = boundingBox.minimum;
  74663. var max = boundingBox.maximum;
  74664. var diff = max.subtract(min);
  74665. var median = min.add(diff.scale(0.5));
  74666. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74667. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74668. .multiply(boundingBox.getWorldMatrix());
  74669. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74670. engine.setDepthFunctionToLess();
  74671. this._scene.resetCachedMaterial();
  74672. this._colorShader.bind(worldMatrix);
  74673. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74674. this._colorShader.unbind();
  74675. engine.setDepthFunctionToLessOrEqual();
  74676. engine.setDepthWrite(true);
  74677. engine.setColorWrite(true);
  74678. };
  74679. BoundingBoxRenderer.prototype.dispose = function () {
  74680. if (!this._colorShader) {
  74681. return;
  74682. }
  74683. this.renderList.dispose();
  74684. this._colorShader.dispose();
  74685. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74686. if (buffer) {
  74687. buffer.dispose();
  74688. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74689. }
  74690. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74691. };
  74692. return BoundingBoxRenderer;
  74693. }());
  74694. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  74695. })(BABYLON || (BABYLON = {}));
  74696. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  74697. var BABYLON;
  74698. (function (BABYLON) {
  74699. var MorphTarget = /** @class */ (function () {
  74700. function MorphTarget(name, influence) {
  74701. if (influence === void 0) { influence = 0; }
  74702. this.name = name;
  74703. this.animations = new Array();
  74704. this._positions = null;
  74705. this._normals = null;
  74706. this._tangents = null;
  74707. this.onInfluenceChanged = new BABYLON.Observable();
  74708. this.influence = influence;
  74709. }
  74710. Object.defineProperty(MorphTarget.prototype, "influence", {
  74711. get: function () {
  74712. return this._influence;
  74713. },
  74714. set: function (influence) {
  74715. if (this._influence === influence) {
  74716. return;
  74717. }
  74718. var previous = this._influence;
  74719. this._influence = influence;
  74720. if (this.onInfluenceChanged.hasObservers) {
  74721. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  74722. }
  74723. },
  74724. enumerable: true,
  74725. configurable: true
  74726. });
  74727. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  74728. get: function () {
  74729. return !!this._positions;
  74730. },
  74731. enumerable: true,
  74732. configurable: true
  74733. });
  74734. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  74735. get: function () {
  74736. return !!this._normals;
  74737. },
  74738. enumerable: true,
  74739. configurable: true
  74740. });
  74741. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  74742. get: function () {
  74743. return !!this._tangents;
  74744. },
  74745. enumerable: true,
  74746. configurable: true
  74747. });
  74748. MorphTarget.prototype.setPositions = function (data) {
  74749. this._positions = data;
  74750. };
  74751. MorphTarget.prototype.getPositions = function () {
  74752. return this._positions;
  74753. };
  74754. MorphTarget.prototype.setNormals = function (data) {
  74755. this._normals = data;
  74756. };
  74757. MorphTarget.prototype.getNormals = function () {
  74758. return this._normals;
  74759. };
  74760. MorphTarget.prototype.setTangents = function (data) {
  74761. this._tangents = data;
  74762. };
  74763. MorphTarget.prototype.getTangents = function () {
  74764. return this._tangents;
  74765. };
  74766. /**
  74767. * Serializes the current target into a Serialization object.
  74768. * Returns the serialized object.
  74769. */
  74770. MorphTarget.prototype.serialize = function () {
  74771. var serializationObject = {};
  74772. serializationObject.name = this.name;
  74773. serializationObject.influence = this.influence;
  74774. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  74775. if (this.hasNormals) {
  74776. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  74777. }
  74778. if (this.hasTangents) {
  74779. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  74780. }
  74781. // Animations
  74782. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  74783. return serializationObject;
  74784. };
  74785. // Statics
  74786. MorphTarget.Parse = function (serializationObject) {
  74787. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  74788. result.setPositions(serializationObject.positions);
  74789. if (serializationObject.normals) {
  74790. result.setNormals(serializationObject.normals);
  74791. }
  74792. if (serializationObject.tangents) {
  74793. result.setTangents(serializationObject.tangents);
  74794. }
  74795. // Animations
  74796. if (serializationObject.animations) {
  74797. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  74798. var parsedAnimation = serializationObject.animations[animationIndex];
  74799. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  74800. }
  74801. }
  74802. return result;
  74803. };
  74804. MorphTarget.FromMesh = function (mesh, name, influence) {
  74805. if (!name) {
  74806. name = mesh.name;
  74807. }
  74808. var result = new MorphTarget(name, influence);
  74809. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74810. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74811. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  74812. }
  74813. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  74814. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  74815. }
  74816. return result;
  74817. };
  74818. return MorphTarget;
  74819. }());
  74820. BABYLON.MorphTarget = MorphTarget;
  74821. })(BABYLON || (BABYLON = {}));
  74822. //# sourceMappingURL=babylon.morphTarget.js.map
  74823. var BABYLON;
  74824. (function (BABYLON) {
  74825. var MorphTargetManager = /** @class */ (function () {
  74826. function MorphTargetManager(scene) {
  74827. if (scene === void 0) { scene = null; }
  74828. this._targets = new Array();
  74829. this._targetObservable = new Array();
  74830. this._activeTargets = new BABYLON.SmartArray(16);
  74831. this._supportsNormals = false;
  74832. this._supportsTangents = false;
  74833. this._vertexCount = 0;
  74834. this._uniqueId = 0;
  74835. this._tempInfluences = new Array();
  74836. if (!scene) {
  74837. scene = BABYLON.Engine.LastCreatedScene;
  74838. }
  74839. this._scene = scene;
  74840. if (this._scene) {
  74841. this._scene.morphTargetManagers.push(this);
  74842. this._uniqueId = this._scene.getUniqueId();
  74843. }
  74844. }
  74845. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  74846. get: function () {
  74847. return this._uniqueId;
  74848. },
  74849. enumerable: true,
  74850. configurable: true
  74851. });
  74852. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  74853. get: function () {
  74854. return this._vertexCount;
  74855. },
  74856. enumerable: true,
  74857. configurable: true
  74858. });
  74859. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  74860. get: function () {
  74861. return this._supportsNormals;
  74862. },
  74863. enumerable: true,
  74864. configurable: true
  74865. });
  74866. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  74867. get: function () {
  74868. return this._supportsTangents;
  74869. },
  74870. enumerable: true,
  74871. configurable: true
  74872. });
  74873. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  74874. get: function () {
  74875. return this._targets.length;
  74876. },
  74877. enumerable: true,
  74878. configurable: true
  74879. });
  74880. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  74881. get: function () {
  74882. return this._activeTargets.length;
  74883. },
  74884. enumerable: true,
  74885. configurable: true
  74886. });
  74887. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  74888. get: function () {
  74889. return this._influences;
  74890. },
  74891. enumerable: true,
  74892. configurable: true
  74893. });
  74894. MorphTargetManager.prototype.getActiveTarget = function (index) {
  74895. return this._activeTargets.data[index];
  74896. };
  74897. MorphTargetManager.prototype.getTarget = function (index) {
  74898. return this._targets[index];
  74899. };
  74900. MorphTargetManager.prototype.addTarget = function (target) {
  74901. var _this = this;
  74902. this._targets.push(target);
  74903. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  74904. _this._syncActiveTargets(needUpdate);
  74905. }));
  74906. this._syncActiveTargets(true);
  74907. };
  74908. MorphTargetManager.prototype.removeTarget = function (target) {
  74909. var index = this._targets.indexOf(target);
  74910. if (index >= 0) {
  74911. this._targets.splice(index, 1);
  74912. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  74913. this._syncActiveTargets(true);
  74914. }
  74915. };
  74916. /**
  74917. * Serializes the current manager into a Serialization object.
  74918. * Returns the serialized object.
  74919. */
  74920. MorphTargetManager.prototype.serialize = function () {
  74921. var serializationObject = {};
  74922. serializationObject.id = this.uniqueId;
  74923. serializationObject.targets = [];
  74924. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74925. var target = _a[_i];
  74926. serializationObject.targets.push(target.serialize());
  74927. }
  74928. return serializationObject;
  74929. };
  74930. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  74931. var influenceCount = 0;
  74932. this._activeTargets.reset();
  74933. this._supportsNormals = true;
  74934. this._supportsTangents = true;
  74935. this._vertexCount = 0;
  74936. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74937. var target = _a[_i];
  74938. this._activeTargets.push(target);
  74939. this._tempInfluences[influenceCount++] = target.influence;
  74940. var positions = target.getPositions();
  74941. if (positions) {
  74942. this._supportsNormals = this._supportsNormals && target.hasNormals;
  74943. this._supportsTangents = this._supportsTangents && target.hasTangents;
  74944. var vertexCount = positions.length / 3;
  74945. if (this._vertexCount === 0) {
  74946. this._vertexCount = vertexCount;
  74947. }
  74948. else if (this._vertexCount !== vertexCount) {
  74949. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  74950. return;
  74951. }
  74952. }
  74953. }
  74954. if (!this._influences || this._influences.length !== influenceCount) {
  74955. this._influences = new Float32Array(influenceCount);
  74956. }
  74957. for (var index = 0; index < influenceCount; index++) {
  74958. this._influences[index] = this._tempInfluences[index];
  74959. }
  74960. if (needUpdate && this._scene) {
  74961. // Flag meshes as dirty to resync with the active targets
  74962. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  74963. var mesh = _c[_b];
  74964. if (mesh.morphTargetManager === this) {
  74965. mesh._syncGeometryWithMorphTargetManager();
  74966. }
  74967. }
  74968. }
  74969. };
  74970. // Statics
  74971. MorphTargetManager.Parse = function (serializationObject, scene) {
  74972. var result = new MorphTargetManager(scene);
  74973. result._uniqueId = serializationObject.id;
  74974. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  74975. var targetData = _a[_i];
  74976. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  74977. }
  74978. return result;
  74979. };
  74980. return MorphTargetManager;
  74981. }());
  74982. BABYLON.MorphTargetManager = MorphTargetManager;
  74983. })(BABYLON || (BABYLON = {}));
  74984. //# sourceMappingURL=babylon.morphTargetManager.js.map
  74985. var BABYLON;
  74986. (function (BABYLON) {
  74987. var Octree = /** @class */ (function () {
  74988. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  74989. if (maxDepth === void 0) { maxDepth = 2; }
  74990. this.maxDepth = maxDepth;
  74991. this.dynamicContent = new Array();
  74992. this._maxBlockCapacity = maxBlockCapacity || 64;
  74993. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  74994. this._creationFunc = creationFunc;
  74995. }
  74996. // Methods
  74997. Octree.prototype.update = function (worldMin, worldMax, entries) {
  74998. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  74999. };
  75000. Octree.prototype.addMesh = function (entry) {
  75001. for (var index = 0; index < this.blocks.length; index++) {
  75002. var block = this.blocks[index];
  75003. block.addEntry(entry);
  75004. }
  75005. };
  75006. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  75007. this._selectionContent.reset();
  75008. for (var index = 0; index < this.blocks.length; index++) {
  75009. var block = this.blocks[index];
  75010. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  75011. }
  75012. if (allowDuplicate) {
  75013. this._selectionContent.concat(this.dynamicContent);
  75014. }
  75015. else {
  75016. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75017. }
  75018. return this._selectionContent;
  75019. };
  75020. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  75021. this._selectionContent.reset();
  75022. for (var index = 0; index < this.blocks.length; index++) {
  75023. var block = this.blocks[index];
  75024. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  75025. }
  75026. if (allowDuplicate) {
  75027. this._selectionContent.concat(this.dynamicContent);
  75028. }
  75029. else {
  75030. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75031. }
  75032. return this._selectionContent;
  75033. };
  75034. Octree.prototype.intersectsRay = function (ray) {
  75035. this._selectionContent.reset();
  75036. for (var index = 0; index < this.blocks.length; index++) {
  75037. var block = this.blocks[index];
  75038. block.intersectsRay(ray, this._selectionContent);
  75039. }
  75040. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75041. return this._selectionContent;
  75042. };
  75043. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  75044. target.blocks = new Array();
  75045. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  75046. // Segmenting space
  75047. for (var x = 0; x < 2; x++) {
  75048. for (var y = 0; y < 2; y++) {
  75049. for (var z = 0; z < 2; z++) {
  75050. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  75051. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  75052. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  75053. block.addEntries(entries);
  75054. target.blocks.push(block);
  75055. }
  75056. }
  75057. }
  75058. };
  75059. Octree.CreationFuncForMeshes = function (entry, block) {
  75060. var boundingInfo = entry.getBoundingInfo();
  75061. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75062. block.entries.push(entry);
  75063. }
  75064. };
  75065. Octree.CreationFuncForSubMeshes = function (entry, block) {
  75066. var boundingInfo = entry.getBoundingInfo();
  75067. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75068. block.entries.push(entry);
  75069. }
  75070. };
  75071. return Octree;
  75072. }());
  75073. BABYLON.Octree = Octree;
  75074. })(BABYLON || (BABYLON = {}));
  75075. //# sourceMappingURL=babylon.octree.js.map
  75076. var BABYLON;
  75077. (function (BABYLON) {
  75078. var OctreeBlock = /** @class */ (function () {
  75079. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  75080. this.entries = new Array();
  75081. this._boundingVectors = new Array();
  75082. this._capacity = capacity;
  75083. this._depth = depth;
  75084. this._maxDepth = maxDepth;
  75085. this._creationFunc = creationFunc;
  75086. this._minPoint = minPoint;
  75087. this._maxPoint = maxPoint;
  75088. this._boundingVectors.push(minPoint.clone());
  75089. this._boundingVectors.push(maxPoint.clone());
  75090. this._boundingVectors.push(minPoint.clone());
  75091. this._boundingVectors[2].x = maxPoint.x;
  75092. this._boundingVectors.push(minPoint.clone());
  75093. this._boundingVectors[3].y = maxPoint.y;
  75094. this._boundingVectors.push(minPoint.clone());
  75095. this._boundingVectors[4].z = maxPoint.z;
  75096. this._boundingVectors.push(maxPoint.clone());
  75097. this._boundingVectors[5].z = minPoint.z;
  75098. this._boundingVectors.push(maxPoint.clone());
  75099. this._boundingVectors[6].x = minPoint.x;
  75100. this._boundingVectors.push(maxPoint.clone());
  75101. this._boundingVectors[7].y = minPoint.y;
  75102. }
  75103. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  75104. // Property
  75105. get: function () {
  75106. return this._capacity;
  75107. },
  75108. enumerable: true,
  75109. configurable: true
  75110. });
  75111. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  75112. get: function () {
  75113. return this._minPoint;
  75114. },
  75115. enumerable: true,
  75116. configurable: true
  75117. });
  75118. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  75119. get: function () {
  75120. return this._maxPoint;
  75121. },
  75122. enumerable: true,
  75123. configurable: true
  75124. });
  75125. // Methods
  75126. OctreeBlock.prototype.addEntry = function (entry) {
  75127. if (this.blocks) {
  75128. for (var index = 0; index < this.blocks.length; index++) {
  75129. var block = this.blocks[index];
  75130. block.addEntry(entry);
  75131. }
  75132. return;
  75133. }
  75134. this._creationFunc(entry, this);
  75135. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  75136. this.createInnerBlocks();
  75137. }
  75138. };
  75139. OctreeBlock.prototype.addEntries = function (entries) {
  75140. for (var index = 0; index < entries.length; index++) {
  75141. var mesh = entries[index];
  75142. this.addEntry(mesh);
  75143. }
  75144. };
  75145. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  75146. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  75147. if (this.blocks) {
  75148. for (var index = 0; index < this.blocks.length; index++) {
  75149. var block = this.blocks[index];
  75150. block.select(frustumPlanes, selection, allowDuplicate);
  75151. }
  75152. return;
  75153. }
  75154. if (allowDuplicate) {
  75155. selection.concat(this.entries);
  75156. }
  75157. else {
  75158. selection.concatWithNoDuplicate(this.entries);
  75159. }
  75160. }
  75161. };
  75162. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  75163. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  75164. if (this.blocks) {
  75165. for (var index = 0; index < this.blocks.length; index++) {
  75166. var block = this.blocks[index];
  75167. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  75168. }
  75169. return;
  75170. }
  75171. if (allowDuplicate) {
  75172. selection.concat(this.entries);
  75173. }
  75174. else {
  75175. selection.concatWithNoDuplicate(this.entries);
  75176. }
  75177. }
  75178. };
  75179. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  75180. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  75181. if (this.blocks) {
  75182. for (var index = 0; index < this.blocks.length; index++) {
  75183. var block = this.blocks[index];
  75184. block.intersectsRay(ray, selection);
  75185. }
  75186. return;
  75187. }
  75188. selection.concatWithNoDuplicate(this.entries);
  75189. }
  75190. };
  75191. OctreeBlock.prototype.createInnerBlocks = function () {
  75192. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  75193. };
  75194. return OctreeBlock;
  75195. }());
  75196. BABYLON.OctreeBlock = OctreeBlock;
  75197. })(BABYLON || (BABYLON = {}));
  75198. //# sourceMappingURL=babylon.octreeBlock.js.map
  75199. var BABYLON;
  75200. (function (BABYLON) {
  75201. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  75202. __extends(VRDistortionCorrectionPostProcess, _super);
  75203. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  75204. var _this = _super.call(this, name, "vrDistortionCorrection", [
  75205. 'LensCenter',
  75206. 'Scale',
  75207. 'ScaleIn',
  75208. 'HmdWarpParam'
  75209. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  75210. _this._isRightEye = isRightEye;
  75211. _this._distortionFactors = vrMetrics.distortionK;
  75212. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  75213. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  75214. _this.adaptScaleToCurrentViewport = true;
  75215. _this.onSizeChangedObservable.add(function () {
  75216. _this.aspectRatio = _this.width * .5 / _this.height;
  75217. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  75218. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  75219. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  75220. });
  75221. _this.onApplyObservable.add(function (effect) {
  75222. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  75223. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  75224. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  75225. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  75226. });
  75227. return _this;
  75228. }
  75229. return VRDistortionCorrectionPostProcess;
  75230. }(BABYLON.PostProcess));
  75231. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  75232. })(BABYLON || (BABYLON = {}));
  75233. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  75234. var BABYLON;
  75235. (function (BABYLON) {
  75236. var AnaglyphPostProcess = /** @class */ (function (_super) {
  75237. __extends(AnaglyphPostProcess, _super);
  75238. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  75239. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  75240. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75241. _this.onApplyObservable.add(function (effect) {
  75242. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  75243. });
  75244. return _this;
  75245. }
  75246. return AnaglyphPostProcess;
  75247. }(BABYLON.PostProcess));
  75248. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  75249. })(BABYLON || (BABYLON = {}));
  75250. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  75251. var BABYLON;
  75252. (function (BABYLON) {
  75253. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  75254. __extends(StereoscopicInterlacePostProcess, _super);
  75255. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  75256. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  75257. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75258. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75259. _this.onSizeChangedObservable.add(function () {
  75260. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75261. });
  75262. _this.onApplyObservable.add(function (effect) {
  75263. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  75264. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  75265. });
  75266. return _this;
  75267. }
  75268. return StereoscopicInterlacePostProcess;
  75269. }(BABYLON.PostProcess));
  75270. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  75271. })(BABYLON || (BABYLON = {}));
  75272. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  75273. var BABYLON;
  75274. (function (BABYLON) {
  75275. /**
  75276. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  75277. * Screen rotation is taken into account.
  75278. */
  75279. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  75280. function FreeCameraDeviceOrientationInput() {
  75281. var _this = this;
  75282. this._screenOrientationAngle = 0;
  75283. this._screenQuaternion = new BABYLON.Quaternion();
  75284. this._alpha = 0;
  75285. this._beta = 0;
  75286. this._gamma = 0;
  75287. this._orientationChanged = function () {
  75288. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  75289. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  75290. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  75291. };
  75292. this._deviceOrientation = function (evt) {
  75293. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  75294. _this._beta = evt.beta !== null ? evt.beta : 0;
  75295. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  75296. };
  75297. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  75298. this._orientationChanged();
  75299. }
  75300. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  75301. get: function () {
  75302. return this._camera;
  75303. },
  75304. set: function (camera) {
  75305. this._camera = camera;
  75306. if (this._camera != null && !this._camera.rotationQuaternion) {
  75307. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  75308. }
  75309. },
  75310. enumerable: true,
  75311. configurable: true
  75312. });
  75313. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75314. window.addEventListener("orientationchange", this._orientationChanged);
  75315. window.addEventListener("deviceorientation", this._deviceOrientation);
  75316. //In certain cases, the attach control is called AFTER orientation was changed,
  75317. //So this is needed.
  75318. this._orientationChanged();
  75319. };
  75320. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  75321. window.removeEventListener("orientationchange", this._orientationChanged);
  75322. window.removeEventListener("deviceorientation", this._deviceOrientation);
  75323. };
  75324. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  75325. //if no device orientation provided, don't update the rotation.
  75326. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  75327. if (!this._alpha)
  75328. return;
  75329. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  75330. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  75331. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  75332. //Mirror on XY Plane
  75333. this._camera.rotationQuaternion.z *= -1;
  75334. this._camera.rotationQuaternion.w *= -1;
  75335. };
  75336. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  75337. return "FreeCameraDeviceOrientationInput";
  75338. };
  75339. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  75340. return "deviceOrientation";
  75341. };
  75342. return FreeCameraDeviceOrientationInput;
  75343. }());
  75344. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  75345. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  75346. })(BABYLON || (BABYLON = {}));
  75347. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  75348. var BABYLON;
  75349. (function (BABYLON) {
  75350. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  75351. function ArcRotateCameraVRDeviceOrientationInput() {
  75352. this.alphaCorrection = 1;
  75353. this.betaCorrection = 1;
  75354. this.gammaCorrection = 1;
  75355. this._alpha = 0;
  75356. this._gamma = 0;
  75357. this._dirty = false;
  75358. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  75359. }
  75360. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75361. this.camera.attachControl(element, noPreventDefault);
  75362. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  75363. };
  75364. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  75365. if (evt.alpha !== null) {
  75366. this._alpha = +evt.alpha | 0;
  75367. }
  75368. if (evt.gamma !== null) {
  75369. this._gamma = +evt.gamma | 0;
  75370. }
  75371. this._dirty = true;
  75372. };
  75373. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  75374. if (this._dirty) {
  75375. this._dirty = false;
  75376. if (this._gamma < 0) {
  75377. this._gamma = 180 + this._gamma;
  75378. }
  75379. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  75380. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  75381. }
  75382. };
  75383. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  75384. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  75385. };
  75386. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  75387. return "ArcRotateCameraVRDeviceOrientationInput";
  75388. };
  75389. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  75390. return "VRDeviceOrientation";
  75391. };
  75392. return ArcRotateCameraVRDeviceOrientationInput;
  75393. }());
  75394. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  75395. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  75396. })(BABYLON || (BABYLON = {}));
  75397. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  75398. var BABYLON;
  75399. (function (BABYLON) {
  75400. var VRCameraMetrics = /** @class */ (function () {
  75401. function VRCameraMetrics() {
  75402. this.compensateDistortion = true;
  75403. }
  75404. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  75405. get: function () {
  75406. return this.hResolution / (2 * this.vResolution);
  75407. },
  75408. enumerable: true,
  75409. configurable: true
  75410. });
  75411. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  75412. get: function () {
  75413. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  75414. },
  75415. enumerable: true,
  75416. configurable: true
  75417. });
  75418. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  75419. get: function () {
  75420. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75421. var h = (4 * meters) / this.hScreenSize;
  75422. return BABYLON.Matrix.Translation(h, 0, 0);
  75423. },
  75424. enumerable: true,
  75425. configurable: true
  75426. });
  75427. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  75428. get: function () {
  75429. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75430. var h = (4 * meters) / this.hScreenSize;
  75431. return BABYLON.Matrix.Translation(-h, 0, 0);
  75432. },
  75433. enumerable: true,
  75434. configurable: true
  75435. });
  75436. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  75437. get: function () {
  75438. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  75444. get: function () {
  75445. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  75446. },
  75447. enumerable: true,
  75448. configurable: true
  75449. });
  75450. VRCameraMetrics.GetDefault = function () {
  75451. var result = new VRCameraMetrics();
  75452. result.hResolution = 1280;
  75453. result.vResolution = 800;
  75454. result.hScreenSize = 0.149759993;
  75455. result.vScreenSize = 0.0935999975;
  75456. result.vScreenCenter = 0.0467999987;
  75457. result.eyeToScreenDistance = 0.0410000011;
  75458. result.lensSeparationDistance = 0.0635000020;
  75459. result.interpupillaryDistance = 0.0640000030;
  75460. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  75461. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  75462. result.postProcessScaleFactor = 1.714605507808412;
  75463. result.lensCenterOffset = 0.151976421;
  75464. return result;
  75465. };
  75466. return VRCameraMetrics;
  75467. }());
  75468. BABYLON.VRCameraMetrics = VRCameraMetrics;
  75469. })(BABYLON || (BABYLON = {}));
  75470. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  75471. var BABYLON;
  75472. (function (BABYLON) {
  75473. /**
  75474. * This represents a WebVR camera.
  75475. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  75476. * @example http://doc.babylonjs.com/how_to/webvr_camera
  75477. */
  75478. var WebVRFreeCamera = /** @class */ (function (_super) {
  75479. __extends(WebVRFreeCamera, _super);
  75480. /**
  75481. * Instantiates a WebVRFreeCamera.
  75482. * @param name The name of the WebVRFreeCamera
  75483. * @param position The starting anchor position for the camera
  75484. * @param scene The scene the camera belongs to
  75485. * @param webVROptions a set of customizable options for the webVRCamera
  75486. */
  75487. function WebVRFreeCamera(name, position, scene, webVROptions) {
  75488. if (webVROptions === void 0) { webVROptions = {}; }
  75489. var _this = _super.call(this, name, position, scene) || this;
  75490. _this.webVROptions = webVROptions;
  75491. /**
  75492. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  75493. */
  75494. _this._vrDevice = null;
  75495. /**
  75496. * The rawPose of the vrDevice.
  75497. */
  75498. _this.rawPose = null;
  75499. _this._specsVersion = "1.1";
  75500. _this._attached = false;
  75501. _this._descendants = [];
  75502. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75503. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75504. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  75505. _this._standingMatrix = null;
  75506. /**
  75507. * Represents device position in babylon space.
  75508. */
  75509. _this.devicePosition = BABYLON.Vector3.Zero();
  75510. /**
  75511. * Represents device rotation in babylon space.
  75512. */
  75513. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  75514. /**
  75515. * The scale of the device to be used when translating from device space to babylon space.
  75516. */
  75517. _this.deviceScaleFactor = 1;
  75518. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75519. _this._worldToDevice = BABYLON.Matrix.Identity();
  75520. /**
  75521. * References to the webVR controllers for the vrDevice.
  75522. */
  75523. _this.controllers = [];
  75524. /**
  75525. * Emits an event when a controller is attached.
  75526. */
  75527. _this.onControllersAttachedObservable = new BABYLON.Observable();
  75528. /**
  75529. * Emits an event when a controller's mesh has been loaded;
  75530. */
  75531. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75532. /**
  75533. * If the rig cameras be used as parent instead of this camera.
  75534. */
  75535. _this.rigParenting = true;
  75536. _this._defaultHeight = undefined;
  75537. _this._workingVector = BABYLON.Vector3.Zero();
  75538. _this._oneVector = BABYLON.Vector3.One();
  75539. _this._workingMatrix = BABYLON.Matrix.Identity();
  75540. _this._cache.position = BABYLON.Vector3.Zero();
  75541. if (webVROptions.defaultHeight) {
  75542. _this._defaultHeight = webVROptions.defaultHeight;
  75543. _this.position.y = _this._defaultHeight;
  75544. }
  75545. _this.minZ = 0.1;
  75546. //legacy support - the compensation boolean was removed.
  75547. if (arguments.length === 5) {
  75548. _this.webVROptions = arguments[4];
  75549. }
  75550. // default webVR options
  75551. if (_this.webVROptions.trackPosition == undefined) {
  75552. _this.webVROptions.trackPosition = true;
  75553. }
  75554. if (_this.webVROptions.controllerMeshes == undefined) {
  75555. _this.webVROptions.controllerMeshes = true;
  75556. }
  75557. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  75558. _this.webVROptions.defaultLightingOnControllers = true;
  75559. }
  75560. _this.rotationQuaternion = new BABYLON.Quaternion();
  75561. if (_this.webVROptions && _this.webVROptions.positionScale) {
  75562. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  75563. }
  75564. //enable VR
  75565. var engine = _this.getEngine();
  75566. _this._onVREnabled = function (success) { if (success) {
  75567. _this.initControllers();
  75568. } };
  75569. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  75570. engine.initWebVR().add(function (event) {
  75571. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  75572. return;
  75573. }
  75574. _this._vrDevice = event.vrDisplay;
  75575. //reset the rig parameters.
  75576. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  75577. if (_this._attached) {
  75578. _this.getEngine().enableVR();
  75579. }
  75580. });
  75581. if (typeof (VRFrameData) !== "undefined")
  75582. _this._frameData = new VRFrameData();
  75583. /**
  75584. * The idea behind the following lines:
  75585. * objects that have the camera as parent should actually have the rig cameras as a parent.
  75586. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  75587. * the second will not show it correctly.
  75588. *
  75589. * To solve this - each object that has the camera as parent will be added to a protected array.
  75590. * When the rig camera renders, it will take this array and set all of those to be its children.
  75591. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  75592. * Amazing!
  75593. */
  75594. scene.onBeforeCameraRenderObservable.add(function (camera) {
  75595. if (camera.parent === _this && _this.rigParenting) {
  75596. _this._descendants = _this.getDescendants(true, function (n) {
  75597. // don't take the cameras or the controllers!
  75598. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  75599. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  75600. return !isController && !isRigCamera;
  75601. });
  75602. _this._descendants.forEach(function (node) {
  75603. node.parent = camera;
  75604. });
  75605. }
  75606. });
  75607. scene.onAfterCameraRenderObservable.add(function (camera) {
  75608. if (camera.parent === _this && _this.rigParenting) {
  75609. _this._descendants.forEach(function (node) {
  75610. node.parent = _this;
  75611. });
  75612. }
  75613. });
  75614. return _this;
  75615. }
  75616. /**
  75617. * Gets the device distance from the ground.
  75618. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  75619. */
  75620. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  75621. if (this._standingMatrix && this._defaultHeight === undefined) {
  75622. // Add standing matrix offset to get real offset from ground in room
  75623. this._standingMatrix.getTranslationToRef(this._workingVector);
  75624. return this._deviceRoomPosition.y + this._workingVector.y;
  75625. }
  75626. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  75627. return this._defaultHeight || 0;
  75628. };
  75629. /**
  75630. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  75631. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  75632. */
  75633. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  75634. var _this = this;
  75635. if (callback === void 0) { callback = function (bool) { }; }
  75636. // Use standing matrix if available
  75637. if (!navigator || !navigator.getVRDisplays) {
  75638. callback(false);
  75639. }
  75640. else {
  75641. navigator.getVRDisplays().then(function (displays) {
  75642. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  75643. callback(false);
  75644. }
  75645. else {
  75646. _this._standingMatrix = new BABYLON.Matrix();
  75647. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  75648. if (!_this.getScene().useRightHandedSystem) {
  75649. [2, 6, 8, 9, 14].forEach(function (num) {
  75650. if (_this._standingMatrix) {
  75651. _this._standingMatrix.m[num] *= -1;
  75652. }
  75653. });
  75654. }
  75655. callback(true);
  75656. }
  75657. });
  75658. }
  75659. };
  75660. /**
  75661. * Disposes the camera
  75662. */
  75663. WebVRFreeCamera.prototype.dispose = function () {
  75664. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  75665. _super.prototype.dispose.call(this);
  75666. };
  75667. /**
  75668. * Gets a vrController by name.
  75669. * @param name The name of the controller to retreive
  75670. * @returns the controller matching the name specified or null if not found
  75671. */
  75672. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  75673. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  75674. var gp = _a[_i];
  75675. if (gp.hand === name) {
  75676. return gp;
  75677. }
  75678. }
  75679. return null;
  75680. };
  75681. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  75682. /**
  75683. * The controller corrisponding to the users left hand.
  75684. */
  75685. get: function () {
  75686. if (!this._leftController) {
  75687. this._leftController = this.getControllerByName("left");
  75688. }
  75689. return this._leftController;
  75690. },
  75691. enumerable: true,
  75692. configurable: true
  75693. });
  75694. ;
  75695. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  75696. /**
  75697. * The controller corrisponding to the users right hand.
  75698. */
  75699. get: function () {
  75700. if (!this._rightController) {
  75701. this._rightController = this.getControllerByName("right");
  75702. }
  75703. return this._rightController;
  75704. },
  75705. enumerable: true,
  75706. configurable: true
  75707. });
  75708. ;
  75709. /**
  75710. * Casts a ray forward from the vrCamera's gaze.
  75711. * @param length Length of the ray (default: 100)
  75712. * @returns the ray corrisponding to the gaze
  75713. */
  75714. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  75715. if (length === void 0) { length = 100; }
  75716. if (this.leftCamera) {
  75717. // Use left eye to avoid computation to compute center on every call
  75718. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  75719. }
  75720. else {
  75721. return _super.prototype.getForwardRay.call(this, length);
  75722. }
  75723. };
  75724. /**
  75725. * Updates the camera based on device's frame data
  75726. */
  75727. WebVRFreeCamera.prototype._checkInputs = function () {
  75728. if (this._vrDevice && this._vrDevice.isPresenting) {
  75729. this._vrDevice.getFrameData(this._frameData);
  75730. this.updateFromDevice(this._frameData.pose);
  75731. }
  75732. _super.prototype._checkInputs.call(this);
  75733. };
  75734. /**
  75735. * Updates the poseControlled values based on the input device pose.
  75736. * @param poseData Pose coming from the device
  75737. */
  75738. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  75739. if (poseData && poseData.orientation) {
  75740. this.rawPose = poseData;
  75741. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  75742. if (this.getScene().useRightHandedSystem) {
  75743. this._deviceRoomRotationQuaternion.z *= -1;
  75744. this._deviceRoomRotationQuaternion.w *= -1;
  75745. }
  75746. if (this.webVROptions.trackPosition && this.rawPose.position) {
  75747. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  75748. if (this.getScene().useRightHandedSystem) {
  75749. this._deviceRoomPosition.z *= -1;
  75750. }
  75751. }
  75752. }
  75753. };
  75754. /**
  75755. * WebVR's attach control will start broadcasting frames to the device.
  75756. * Note that in certain browsers (chrome for example) this function must be called
  75757. * within a user-interaction callback. Example:
  75758. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  75759. *
  75760. * @param element html element to attach the vrDevice to
  75761. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  75762. */
  75763. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  75764. _super.prototype.attachControl.call(this, element, noPreventDefault);
  75765. this._attached = true;
  75766. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  75767. if (this._vrDevice) {
  75768. this.getEngine().enableVR();
  75769. }
  75770. };
  75771. /**
  75772. * Detaches the camera from the html element and disables VR
  75773. *
  75774. * @param element html element to detach from
  75775. */
  75776. WebVRFreeCamera.prototype.detachControl = function (element) {
  75777. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75778. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75779. _super.prototype.detachControl.call(this, element);
  75780. this._attached = false;
  75781. this.getEngine().disableVR();
  75782. };
  75783. /**
  75784. * @returns the name of this class
  75785. */
  75786. WebVRFreeCamera.prototype.getClassName = function () {
  75787. return "WebVRFreeCamera";
  75788. };
  75789. /**
  75790. * Calls resetPose on the vrDisplay
  75791. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  75792. */
  75793. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  75794. //uses the vrDisplay's "resetPose()".
  75795. //pitch and roll won't be affected.
  75796. this._vrDevice.resetPose();
  75797. };
  75798. /**
  75799. * Updates the rig cameras (left and right eye)
  75800. */
  75801. WebVRFreeCamera.prototype._updateRigCameras = function () {
  75802. var camLeft = this._rigCameras[0];
  75803. var camRight = this._rigCameras[1];
  75804. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75805. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75806. camLeft.position.copyFrom(this._deviceRoomPosition);
  75807. camRight.position.copyFrom(this._deviceRoomPosition);
  75808. };
  75809. /**
  75810. * Updates the cached values of the camera
  75811. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  75812. */
  75813. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  75814. var _this = this;
  75815. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  75816. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  75817. if (!this.updateCacheCalled) {
  75818. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  75819. this.updateCacheCalled = true;
  75820. this.update();
  75821. }
  75822. // Set working vector to the device position in room space rotated by the new rotation
  75823. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  75824. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  75825. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  75826. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  75827. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  75828. // Add translation from anchor position
  75829. this._deviceToWorld.getTranslationToRef(this._workingVector);
  75830. this._workingVector.addInPlace(this.position);
  75831. this._workingVector.subtractInPlace(this._cache.position);
  75832. this._deviceToWorld.setTranslation(this._workingVector);
  75833. // Set an inverted matrix to be used when updating the camera
  75834. this._deviceToWorld.invertToRef(this._worldToDevice);
  75835. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  75836. this.controllers.forEach(function (controller) {
  75837. controller._deviceToWorld = _this._deviceToWorld;
  75838. controller.update();
  75839. });
  75840. }
  75841. if (!ignoreParentClass) {
  75842. _super.prototype._updateCache.call(this);
  75843. }
  75844. this.updateCacheCalled = false;
  75845. };
  75846. /**
  75847. * Updates the current device position and rotation in the babylon world
  75848. */
  75849. WebVRFreeCamera.prototype.update = function () {
  75850. // Get current device position in babylon world
  75851. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  75852. // Get current device rotation in babylon world
  75853. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  75854. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  75855. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75856. _super.prototype.update.call(this);
  75857. };
  75858. /**
  75859. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  75860. * @returns an identity matrix
  75861. */
  75862. WebVRFreeCamera.prototype._getViewMatrix = function () {
  75863. return BABYLON.Matrix.Identity();
  75864. };
  75865. /**
  75866. * This function is called by the two RIG cameras.
  75867. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  75868. */
  75869. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  75870. var _this = this;
  75871. //WebVR 1.1
  75872. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  75873. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  75874. if (!this.getScene().useRightHandedSystem) {
  75875. [2, 6, 8, 9, 14].forEach(function (num) {
  75876. _this._webvrViewMatrix.m[num] *= -1;
  75877. });
  75878. }
  75879. // update the camera rotation matrix
  75880. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  75881. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  75882. // Computing target and final matrix
  75883. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  75884. var parentCamera = this._cameraRigParams["parentCamera"];
  75885. // should the view matrix be updated with scale and position offset?
  75886. if (parentCamera.deviceScaleFactor !== 1) {
  75887. this._webvrViewMatrix.invert();
  75888. // scale the position, if set
  75889. if (parentCamera.deviceScaleFactor) {
  75890. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  75891. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  75892. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  75893. }
  75894. this._webvrViewMatrix.invert();
  75895. }
  75896. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  75897. return this._webvrViewMatrix;
  75898. };
  75899. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  75900. var _this = this;
  75901. var parentCamera = this.parent;
  75902. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  75903. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  75904. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  75905. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  75906. //babylon compatible matrix
  75907. if (!this.getScene().useRightHandedSystem) {
  75908. [8, 9, 10, 11].forEach(function (num) {
  75909. _this._projectionMatrix.m[num] *= -1;
  75910. });
  75911. }
  75912. return this._projectionMatrix;
  75913. };
  75914. /**
  75915. * Initializes the controllers and their meshes
  75916. */
  75917. WebVRFreeCamera.prototype.initControllers = function () {
  75918. var _this = this;
  75919. this.controllers = [];
  75920. var manager = this.getScene().gamepadManager;
  75921. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75922. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75923. var webVrController = gamepad;
  75924. if (webVrController.defaultModel) {
  75925. webVrController.defaultModel.setEnabled(false);
  75926. }
  75927. if (webVrController.hand === "right") {
  75928. _this._rightController = null;
  75929. }
  75930. if (webVrController.hand === "left") {
  75931. _this._rightController = null;
  75932. }
  75933. var controllerIndex = _this.controllers.indexOf(webVrController);
  75934. if (controllerIndex !== -1) {
  75935. _this.controllers.splice(controllerIndex, 1);
  75936. }
  75937. }
  75938. });
  75939. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75940. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75941. var webVrController_1 = gamepad;
  75942. webVrController_1._deviceToWorld = _this._deviceToWorld;
  75943. if (_this.webVROptions.controllerMeshes) {
  75944. if (webVrController_1.defaultModel) {
  75945. webVrController_1.defaultModel.setEnabled(true);
  75946. }
  75947. else {
  75948. // Load the meshes
  75949. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  75950. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  75951. if (_this.webVROptions.defaultLightingOnControllers) {
  75952. if (!_this._lightOnControllers) {
  75953. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  75954. }
  75955. var activateLightOnSubMeshes_1 = function (mesh, light) {
  75956. var children = mesh.getChildren();
  75957. if (children.length !== 0) {
  75958. children.forEach(function (mesh) {
  75959. light.includedOnlyMeshes.push(mesh);
  75960. activateLightOnSubMeshes_1(mesh, light);
  75961. });
  75962. }
  75963. };
  75964. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  75965. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  75966. }
  75967. });
  75968. }
  75969. }
  75970. webVrController_1.attachToPoseControlledCamera(_this);
  75971. // since this is async - sanity check. Is the controller already stored?
  75972. if (_this.controllers.indexOf(webVrController_1) === -1) {
  75973. //add to the controllers array
  75974. _this.controllers.push(webVrController_1);
  75975. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  75976. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  75977. // So we're overriding setting left & right manually to be sure
  75978. var firstViveWandDetected = false;
  75979. for (var i = 0; i < _this.controllers.length; i++) {
  75980. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75981. if (!firstViveWandDetected) {
  75982. firstViveWandDetected = true;
  75983. _this.controllers[i].hand = "left";
  75984. }
  75985. else {
  75986. _this.controllers[i].hand = "right";
  75987. }
  75988. }
  75989. }
  75990. //did we find enough controllers? Great! let the developer know.
  75991. if (_this.controllers.length >= 2) {
  75992. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  75993. }
  75994. }
  75995. }
  75996. });
  75997. };
  75998. return WebVRFreeCamera;
  75999. }(BABYLON.FreeCamera));
  76000. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  76001. })(BABYLON || (BABYLON = {}));
  76002. //# sourceMappingURL=babylon.webVRCamera.js.map
  76003. var BABYLON;
  76004. (function (BABYLON) {
  76005. // We're mainly based on the logic defined into the FreeCamera code
  76006. /**
  76007. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  76008. * being tilted forward or back and left or right.
  76009. */
  76010. var DeviceOrientationCamera = /** @class */ (function (_super) {
  76011. __extends(DeviceOrientationCamera, _super);
  76012. /**
  76013. * Creates a new device orientation camera. @see DeviceOrientationCamera
  76014. * @param name The name of the camera
  76015. * @param position The start position camera
  76016. * @param scene The scene the camera belongs to
  76017. */
  76018. function DeviceOrientationCamera(name, position, scene) {
  76019. var _this = _super.call(this, name, position, scene) || this;
  76020. _this._quaternionCache = new BABYLON.Quaternion();
  76021. _this.inputs.addDeviceOrientation();
  76022. return _this;
  76023. }
  76024. /**
  76025. * Gets the current instance class name ("DeviceOrientationCamera").
  76026. * This helps avoiding instanceof at run time.
  76027. * @returns the class name
  76028. */
  76029. DeviceOrientationCamera.prototype.getClassName = function () {
  76030. return "DeviceOrientationCamera";
  76031. };
  76032. /**
  76033. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  76034. */
  76035. DeviceOrientationCamera.prototype._checkInputs = function () {
  76036. _super.prototype._checkInputs.call(this);
  76037. this._quaternionCache.copyFrom(this.rotationQuaternion);
  76038. if (this._initialQuaternion) {
  76039. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76040. }
  76041. };
  76042. /**
  76043. * Reset the camera to its default orientation on the specified axis only.
  76044. * @param axis The axis to reset
  76045. */
  76046. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  76047. var _this = this;
  76048. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  76049. //can only work if this camera has a rotation quaternion already.
  76050. if (!this.rotationQuaternion)
  76051. return;
  76052. if (!this._initialQuaternion) {
  76053. this._initialQuaternion = new BABYLON.Quaternion();
  76054. }
  76055. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  76056. ['x', 'y', 'z'].forEach(function (axisName) {
  76057. if (!axis[axisName]) {
  76058. _this._initialQuaternion[axisName] = 0;
  76059. }
  76060. else {
  76061. _this._initialQuaternion[axisName] *= -1;
  76062. }
  76063. });
  76064. this._initialQuaternion.normalize();
  76065. //force rotation update
  76066. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76067. };
  76068. return DeviceOrientationCamera;
  76069. }(BABYLON.FreeCamera));
  76070. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  76071. })(BABYLON || (BABYLON = {}));
  76072. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  76073. var BABYLON;
  76074. (function (BABYLON) {
  76075. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  76076. __extends(VRDeviceOrientationFreeCamera, _super);
  76077. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76078. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76079. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76080. var _this = _super.call(this, name, position, scene) || this;
  76081. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76082. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76083. return _this;
  76084. }
  76085. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  76086. return "VRDeviceOrientationFreeCamera";
  76087. };
  76088. return VRDeviceOrientationFreeCamera;
  76089. }(BABYLON.DeviceOrientationCamera));
  76090. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  76091. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  76092. __extends(VRDeviceOrientationGamepadCamera, _super);
  76093. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76094. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76095. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76096. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  76097. _this.inputs.addGamepad();
  76098. return _this;
  76099. }
  76100. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  76101. return "VRDeviceOrientationGamepadCamera";
  76102. };
  76103. return VRDeviceOrientationGamepadCamera;
  76104. }(VRDeviceOrientationFreeCamera));
  76105. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  76106. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  76107. __extends(VRDeviceOrientationArcRotateCamera, _super);
  76108. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  76109. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76110. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76111. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76112. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76113. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76114. _this.inputs.addVRDeviceOrientation();
  76115. return _this;
  76116. }
  76117. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  76118. return "VRDeviceOrientationArcRotateCamera";
  76119. };
  76120. return VRDeviceOrientationArcRotateCamera;
  76121. }(BABYLON.ArcRotateCamera));
  76122. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  76123. })(BABYLON || (BABYLON = {}));
  76124. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  76125. var BABYLON;
  76126. (function (BABYLON) {
  76127. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  76128. __extends(AnaglyphFreeCamera, _super);
  76129. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  76130. var _this = _super.call(this, name, position, scene) || this;
  76131. _this.interaxialDistance = interaxialDistance;
  76132. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76133. return _this;
  76134. }
  76135. AnaglyphFreeCamera.prototype.getClassName = function () {
  76136. return "AnaglyphFreeCamera";
  76137. };
  76138. return AnaglyphFreeCamera;
  76139. }(BABYLON.FreeCamera));
  76140. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  76141. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  76142. __extends(AnaglyphArcRotateCamera, _super);
  76143. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  76144. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76145. _this.interaxialDistance = interaxialDistance;
  76146. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76147. return _this;
  76148. }
  76149. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  76150. return "AnaglyphArcRotateCamera";
  76151. };
  76152. return AnaglyphArcRotateCamera;
  76153. }(BABYLON.ArcRotateCamera));
  76154. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  76155. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  76156. __extends(AnaglyphGamepadCamera, _super);
  76157. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  76158. var _this = _super.call(this, name, position, scene) || this;
  76159. _this.interaxialDistance = interaxialDistance;
  76160. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76161. return _this;
  76162. }
  76163. AnaglyphGamepadCamera.prototype.getClassName = function () {
  76164. return "AnaglyphGamepadCamera";
  76165. };
  76166. return AnaglyphGamepadCamera;
  76167. }(BABYLON.GamepadCamera));
  76168. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  76169. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  76170. __extends(AnaglyphUniversalCamera, _super);
  76171. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  76172. var _this = _super.call(this, name, position, scene) || this;
  76173. _this.interaxialDistance = interaxialDistance;
  76174. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76175. return _this;
  76176. }
  76177. AnaglyphUniversalCamera.prototype.getClassName = function () {
  76178. return "AnaglyphUniversalCamera";
  76179. };
  76180. return AnaglyphUniversalCamera;
  76181. }(BABYLON.UniversalCamera));
  76182. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  76183. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  76184. __extends(StereoscopicFreeCamera, _super);
  76185. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76186. var _this = _super.call(this, name, position, scene) || this;
  76187. _this.interaxialDistance = interaxialDistance;
  76188. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76189. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76190. return _this;
  76191. }
  76192. StereoscopicFreeCamera.prototype.getClassName = function () {
  76193. return "StereoscopicFreeCamera";
  76194. };
  76195. return StereoscopicFreeCamera;
  76196. }(BABYLON.FreeCamera));
  76197. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  76198. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  76199. __extends(StereoscopicArcRotateCamera, _super);
  76200. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  76201. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76202. _this.interaxialDistance = interaxialDistance;
  76203. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76204. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76205. return _this;
  76206. }
  76207. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  76208. return "StereoscopicArcRotateCamera";
  76209. };
  76210. return StereoscopicArcRotateCamera;
  76211. }(BABYLON.ArcRotateCamera));
  76212. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  76213. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  76214. __extends(StereoscopicGamepadCamera, _super);
  76215. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76216. var _this = _super.call(this, name, position, scene) || this;
  76217. _this.interaxialDistance = interaxialDistance;
  76218. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76219. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76220. return _this;
  76221. }
  76222. StereoscopicGamepadCamera.prototype.getClassName = function () {
  76223. return "StereoscopicGamepadCamera";
  76224. };
  76225. return StereoscopicGamepadCamera;
  76226. }(BABYLON.GamepadCamera));
  76227. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  76228. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  76229. __extends(StereoscopicUniversalCamera, _super);
  76230. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76231. var _this = _super.call(this, name, position, scene) || this;
  76232. _this.interaxialDistance = interaxialDistance;
  76233. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76234. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76235. return _this;
  76236. }
  76237. StereoscopicUniversalCamera.prototype.getClassName = function () {
  76238. return "StereoscopicUniversalCamera";
  76239. };
  76240. return StereoscopicUniversalCamera;
  76241. }(BABYLON.UniversalCamera));
  76242. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  76243. })(BABYLON || (BABYLON = {}));
  76244. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  76245. var BABYLON;
  76246. (function (BABYLON) {
  76247. /**
  76248. * Helps to quickly add VR support to an existing scene.
  76249. * See http://doc.babylonjs.com/how_to/webvr_helper
  76250. */
  76251. var VRExperienceHelper = /** @class */ (function () {
  76252. /**
  76253. * Instantiates a VRExperienceHelper.
  76254. * Helps to quickly add VR support to an existing scene.
  76255. * @param scene The scene the VRExperienceHelper belongs to.
  76256. * @param webVROptions Options to modify the vr experience helper's behavior.
  76257. */
  76258. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  76259. if (webVROptions === void 0) { webVROptions = {}; }
  76260. var _this = this;
  76261. this.webVROptions = webVROptions;
  76262. // Can the system support WebVR, even if a headset isn't plugged in?
  76263. this._webVRsupported = false;
  76264. // If WebVR is supported, is a headset plugged in and are we ready to present?
  76265. this._webVRready = false;
  76266. // Are we waiting for the requestPresent callback to complete?
  76267. this._webVRrequesting = false;
  76268. // Are we presenting to the headset right now?
  76269. this._webVRpresenting = false;
  76270. // Are we presenting in the fullscreen fallback?
  76271. this._fullscreenVRpresenting = false;
  76272. /**
  76273. * Observable raised when entering VR.
  76274. */
  76275. this.onEnteringVRObservable = new BABYLON.Observable();
  76276. /**
  76277. * Observable raised when exiting VR.
  76278. */
  76279. this.onExitingVRObservable = new BABYLON.Observable();
  76280. /**
  76281. * Observable raised when controller mesh is loaded.
  76282. */
  76283. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76284. this._useCustomVRButton = false;
  76285. this._teleportationRequested = false;
  76286. this._teleportationEnabledOnLeftController = false;
  76287. this._teleportationEnabledOnRightController = false;
  76288. this._interactionsEnabledOnLeftController = false;
  76289. this._interactionsEnabledOnRightController = false;
  76290. this._leftControllerReady = false;
  76291. this._rightControllerReady = false;
  76292. this._floorMeshesCollection = [];
  76293. this._teleportationAllowed = false;
  76294. this._rotationAllowed = true;
  76295. this._teleportationRequestInitiated = false;
  76296. this._teleportationBackRequestInitiated = false;
  76297. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  76298. this._rotationRightAsked = false;
  76299. this._rotationLeftAsked = false;
  76300. this._isDefaultTeleportationTarget = true;
  76301. this._teleportationFillColor = "#444444";
  76302. this._teleportationBorderColor = "#FFFFFF";
  76303. this._rotationAngle = 0;
  76304. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  76305. this._padSensibilityUp = 0.65;
  76306. this._padSensibilityDown = 0.35;
  76307. /**
  76308. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  76309. */
  76310. this.onNewMeshSelected = new BABYLON.Observable();
  76311. /**
  76312. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  76313. */
  76314. this.onNewMeshPicked = new BABYLON.Observable();
  76315. /**
  76316. * Observable raised before camera teleportation
  76317. */
  76318. this.onBeforeCameraTeleport = new BABYLON.Observable();
  76319. /**
  76320. * Observable raised after camera teleportation
  76321. */
  76322. this.onAfterCameraTeleport = new BABYLON.Observable();
  76323. /**
  76324. * Observable raised when current selected mesh gets unselected
  76325. */
  76326. this.onSelectedMeshUnselected = new BABYLON.Observable();
  76327. /**
  76328. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  76329. */
  76330. this.teleportationEnabled = true;
  76331. this._pointerDownOnMeshAsked = false;
  76332. this._isActionableMesh = false;
  76333. this._teleportationInitialized = false;
  76334. this._interactionsEnabled = false;
  76335. this._interactionsRequested = false;
  76336. this._displayGaze = true;
  76337. this._displayLaserPointer = true;
  76338. this._dpadPressed = true;
  76339. this._onResize = function () {
  76340. _this.moveButtonToBottomRight();
  76341. if (_this._fullscreenVRpresenting && _this._webVRready) {
  76342. _this.exitVR();
  76343. }
  76344. };
  76345. this._onFullscreenChange = function () {
  76346. if (document.fullscreen !== undefined) {
  76347. _this._fullscreenVRpresenting = document.fullscreen;
  76348. }
  76349. else if (document.mozFullScreen !== undefined) {
  76350. _this._fullscreenVRpresenting = document.mozFullScreen;
  76351. }
  76352. else if (document.webkitIsFullScreen !== undefined) {
  76353. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  76354. }
  76355. else if (document.msIsFullScreen !== undefined) {
  76356. _this._fullscreenVRpresenting = document.msIsFullScreen;
  76357. }
  76358. if (!_this._fullscreenVRpresenting && _this._canvas) {
  76359. _this.exitVR();
  76360. if (!_this._useCustomVRButton) {
  76361. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  76362. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  76363. }
  76364. }
  76365. };
  76366. this.beforeRender = function () {
  76367. _this._castRayAndSelectObject();
  76368. };
  76369. this._onNewGamepadConnected = function (gamepad) {
  76370. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76371. if (gamepad.leftStick) {
  76372. gamepad.onleftstickchanged(function (stickValues) {
  76373. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  76374. // Listening to classic/xbox gamepad only if no VR controller is active
  76375. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  76376. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  76377. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  76378. _this._checkTeleportWithRay(stickValues);
  76379. _this._checkTeleportBackwards(stickValues);
  76380. }
  76381. }
  76382. });
  76383. }
  76384. if (gamepad.rightStick) {
  76385. gamepad.onrightstickchanged(function (stickValues) {
  76386. if (_this._teleportationInitialized) {
  76387. _this._checkRotate(stickValues);
  76388. }
  76389. });
  76390. }
  76391. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  76392. gamepad.onbuttondown(function (buttonPressed) {
  76393. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76394. _this._selectionPointerDown();
  76395. }
  76396. });
  76397. gamepad.onbuttonup(function (buttonPressed) {
  76398. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76399. _this._selectionPointerUp();
  76400. }
  76401. });
  76402. }
  76403. }
  76404. else {
  76405. var webVRController = gamepad;
  76406. _this._tryEnableInteractionOnController(webVRController);
  76407. }
  76408. };
  76409. // 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
  76410. this._tryEnableInteractionOnController = function (webVRController) {
  76411. if (webVRController.hand === "left") {
  76412. _this._leftControllerReady = true;
  76413. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  76414. _this._enableInteractionOnController(webVRController);
  76415. }
  76416. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  76417. _this._enableTeleportationOnController(webVRController);
  76418. }
  76419. }
  76420. if (webVRController.hand === "right") {
  76421. _this._rightControllerReady = true;
  76422. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  76423. _this._enableInteractionOnController(webVRController);
  76424. }
  76425. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  76426. _this._enableTeleportationOnController(webVRController);
  76427. }
  76428. }
  76429. };
  76430. this._onNewGamepadDisconnected = function (gamepad) {
  76431. if (gamepad instanceof BABYLON.WebVRController) {
  76432. if (gamepad.hand === "left") {
  76433. _this._interactionsEnabledOnLeftController = false;
  76434. _this._teleportationEnabledOnLeftController = false;
  76435. _this._leftControllerReady = false;
  76436. if (_this._leftLaserPointer) {
  76437. _this._leftLaserPointer.dispose();
  76438. }
  76439. }
  76440. if (gamepad.hand === "right") {
  76441. _this._interactionsEnabledOnRightController = false;
  76442. _this._teleportationEnabledOnRightController = false;
  76443. _this._rightControllerReady = false;
  76444. if (_this._rightLaserPointer) {
  76445. _this._rightLaserPointer.dispose();
  76446. }
  76447. }
  76448. }
  76449. };
  76450. this._workingVector = BABYLON.Vector3.Zero();
  76451. this._workingQuaternion = BABYLON.Quaternion.Identity();
  76452. this._workingMatrix = BABYLON.Matrix.Identity();
  76453. this._scene = scene;
  76454. this._canvas = scene.getEngine().getRenderingCanvas();
  76455. // Parse options
  76456. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  76457. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  76458. }
  76459. if (webVROptions.createDeviceOrientationCamera === undefined) {
  76460. webVROptions.createDeviceOrientationCamera = true;
  76461. }
  76462. if (webVROptions.defaultHeight === undefined) {
  76463. webVROptions.defaultHeight = 1.7;
  76464. }
  76465. if (webVROptions.useCustomVRButton) {
  76466. this._useCustomVRButton = true;
  76467. if (webVROptions.customVRButton) {
  76468. this._btnVR = webVROptions.customVRButton;
  76469. }
  76470. }
  76471. if (webVROptions.rayLength) {
  76472. this._rayLength = webVROptions.rayLength;
  76473. }
  76474. this._defaultHeight = webVROptions.defaultHeight;
  76475. // Set position
  76476. if (this._scene.activeCamera) {
  76477. this._position = this._scene.activeCamera.position.clone();
  76478. }
  76479. else {
  76480. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  76481. }
  76482. // Set non-vr camera
  76483. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  76484. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  76485. // Copy data from existing camera
  76486. if (this._scene.activeCamera) {
  76487. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  76488. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  76489. // Set rotation from previous camera
  76490. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  76491. var targetCamera = this._scene.activeCamera;
  76492. if (targetCamera.rotationQuaternion) {
  76493. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  76494. }
  76495. else {
  76496. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  76497. }
  76498. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  76499. }
  76500. }
  76501. this._scene.activeCamera = this._deviceOrientationCamera;
  76502. if (this._canvas) {
  76503. this._scene.activeCamera.attachControl(this._canvas);
  76504. }
  76505. }
  76506. else {
  76507. this._existingCamera = this._scene.activeCamera;
  76508. }
  76509. // Create VR cameras
  76510. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76511. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  76512. }
  76513. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  76514. this._webVRCamera.useStandingMatrix();
  76515. // Create default button
  76516. if (!this._useCustomVRButton) {
  76517. this._btnVR = document.createElement("BUTTON");
  76518. this._btnVR.className = "babylonVRicon";
  76519. this._btnVR.id = "babylonVRiconbtn";
  76520. this._btnVR.title = "Click to switch to VR";
  76521. 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) }";
  76522. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  76523. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  76524. // css += ".babylonVRicon.vrdisplaysupported { }";
  76525. // css += ".babylonVRicon.vrdisplayready { }";
  76526. // css += ".babylonVRicon.vrdisplayrequesting { }";
  76527. var style = document.createElement('style');
  76528. style.appendChild(document.createTextNode(css));
  76529. document.getElementsByTagName('head')[0].appendChild(style);
  76530. this.moveButtonToBottomRight();
  76531. }
  76532. // VR button click event
  76533. if (this._btnVR) {
  76534. this._btnVR.addEventListener("click", function () {
  76535. if (!_this.isInVRMode) {
  76536. _this.enterVR();
  76537. }
  76538. else {
  76539. _this.exitVR();
  76540. }
  76541. });
  76542. }
  76543. // Window events
  76544. window.addEventListener("resize", this._onResize);
  76545. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  76546. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  76547. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  76548. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  76549. // Display vr button when headset is connected
  76550. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76551. this.displayVRButton();
  76552. }
  76553. else {
  76554. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  76555. if (e.vrDisplay) {
  76556. _this.displayVRButton();
  76557. }
  76558. });
  76559. }
  76560. // Exiting VR mode using 'ESC' key on desktop
  76561. this._onKeyDown = function (event) {
  76562. if (event.keyCode === 27 && _this.isInVRMode) {
  76563. _this.exitVR();
  76564. }
  76565. };
  76566. document.addEventListener("keydown", this._onKeyDown);
  76567. // Exiting VR mode double tapping the touch screen
  76568. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  76569. if (_this.isInVRMode) {
  76570. _this.exitVR();
  76571. if (_this._fullscreenVRpresenting) {
  76572. _this._scene.getEngine().switchFullscreen(true);
  76573. }
  76574. }
  76575. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  76576. // Listen for WebVR display changes
  76577. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  76578. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  76579. this._onVRRequestPresentStart = function () {
  76580. _this._webVRrequesting = true;
  76581. _this.updateButtonVisibility();
  76582. };
  76583. this._onVRRequestPresentComplete = function (success) {
  76584. _this._webVRrequesting = false;
  76585. _this.updateButtonVisibility();
  76586. };
  76587. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  76588. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  76589. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  76590. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76591. scene.onDisposeObservable.add(function () {
  76592. _this.dispose();
  76593. });
  76594. // Gamepad connection events
  76595. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  76596. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  76597. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  76598. this.updateButtonVisibility();
  76599. //create easing functions
  76600. this._circleEase = new BABYLON.CircleEase();
  76601. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76602. }
  76603. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  76604. /** Return this.onEnteringVRObservable
  76605. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  76606. */
  76607. get: function () {
  76608. return this.onEnteringVRObservable;
  76609. },
  76610. enumerable: true,
  76611. configurable: true
  76612. });
  76613. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  76614. /** Return this.onExitingVRObservable
  76615. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  76616. */
  76617. get: function () {
  76618. return this.onExitingVRObservable;
  76619. },
  76620. enumerable: true,
  76621. configurable: true
  76622. });
  76623. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  76624. /** Return this.onControllerMeshLoadedObservable
  76625. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  76626. */
  76627. get: function () {
  76628. return this.onControllerMeshLoadedObservable;
  76629. },
  76630. enumerable: true,
  76631. configurable: true
  76632. });
  76633. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  76634. /**
  76635. * The mesh used to display where the user is going to teleport.
  76636. */
  76637. get: function () {
  76638. return this._teleportationTarget;
  76639. },
  76640. /**
  76641. * Sets the mesh to be used to display where the user is going to teleport.
  76642. */
  76643. set: function (value) {
  76644. if (value) {
  76645. value.name = "teleportationTarget";
  76646. this._isDefaultTeleportationTarget = false;
  76647. this._teleportationTarget = value;
  76648. }
  76649. },
  76650. enumerable: true,
  76651. configurable: true
  76652. });
  76653. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  76654. /**
  76655. * If the ray of the gaze should be displayed.
  76656. */
  76657. get: function () {
  76658. return this._displayGaze;
  76659. },
  76660. /**
  76661. * Sets if the ray of the gaze should be displayed.
  76662. */
  76663. set: function (value) {
  76664. this._displayGaze = value;
  76665. if (!value) {
  76666. this._gazeTracker.isVisible = false;
  76667. }
  76668. },
  76669. enumerable: true,
  76670. configurable: true
  76671. });
  76672. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  76673. /**
  76674. * If the ray of the LaserPointer should be displayed.
  76675. */
  76676. get: function () {
  76677. return this._displayLaserPointer;
  76678. },
  76679. /**
  76680. * Sets if the ray of the LaserPointer should be displayed.
  76681. */
  76682. set: function (value) {
  76683. this._displayLaserPointer = value;
  76684. if (!value) {
  76685. if (this._rightLaserPointer) {
  76686. this._rightLaserPointer.isVisible = false;
  76687. }
  76688. if (this._leftLaserPointer) {
  76689. this._leftLaserPointer.isVisible = false;
  76690. }
  76691. }
  76692. else {
  76693. if (this._rightLaserPointer) {
  76694. this._rightLaserPointer.isVisible = true;
  76695. }
  76696. else if (this._leftLaserPointer) {
  76697. this._leftLaserPointer.isVisible = true;
  76698. }
  76699. }
  76700. },
  76701. enumerable: true,
  76702. configurable: true
  76703. });
  76704. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  76705. /**
  76706. * The deviceOrientationCamera used as the camera when not in VR.
  76707. */
  76708. get: function () {
  76709. return this._deviceOrientationCamera;
  76710. },
  76711. enumerable: true,
  76712. configurable: true
  76713. });
  76714. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  76715. /**
  76716. * Based on the current WebVR support, returns the current VR camera used.
  76717. */
  76718. get: function () {
  76719. if (this._webVRready) {
  76720. return this._webVRCamera;
  76721. }
  76722. else {
  76723. return this._scene.activeCamera;
  76724. }
  76725. },
  76726. enumerable: true,
  76727. configurable: true
  76728. });
  76729. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  76730. /**
  76731. * The webVRCamera which is used when in VR.
  76732. */
  76733. get: function () {
  76734. return this._webVRCamera;
  76735. },
  76736. enumerable: true,
  76737. configurable: true
  76738. });
  76739. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  76740. /**
  76741. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  76742. */
  76743. get: function () {
  76744. return this._vrDeviceOrientationCamera;
  76745. },
  76746. enumerable: true,
  76747. configurable: true
  76748. });
  76749. // Raised when one of the controller has loaded successfully its associated default mesh
  76750. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  76751. this._tryEnableInteractionOnController(webVRController);
  76752. try {
  76753. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  76754. }
  76755. catch (err) {
  76756. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  76757. }
  76758. };
  76759. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  76760. /**
  76761. * Gets a value indicating if we are currently in VR mode.
  76762. */
  76763. get: function () {
  76764. return this._webVRpresenting || this._fullscreenVRpresenting;
  76765. },
  76766. enumerable: true,
  76767. configurable: true
  76768. });
  76769. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  76770. var vrDisplay = this._scene.getEngine().getVRDevice();
  76771. if (vrDisplay) {
  76772. var wasPresenting = this._webVRpresenting;
  76773. // A VR display is connected
  76774. this._webVRpresenting = vrDisplay.isPresenting;
  76775. if (wasPresenting && !this._webVRpresenting)
  76776. this.exitVR();
  76777. }
  76778. else {
  76779. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  76780. }
  76781. this.updateButtonVisibility();
  76782. };
  76783. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  76784. this._webVRsupported = eventArgs.vrSupported;
  76785. this._webVRready = !!eventArgs.vrDisplay;
  76786. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  76787. this.updateButtonVisibility();
  76788. };
  76789. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  76790. if (this._canvas && !this._useCustomVRButton) {
  76791. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  76792. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  76793. }
  76794. };
  76795. VRExperienceHelper.prototype.displayVRButton = function () {
  76796. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  76797. document.body.appendChild(this._btnVR);
  76798. this._btnVRDisplayed = true;
  76799. }
  76800. };
  76801. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  76802. if (!this._btnVR || this._useCustomVRButton) {
  76803. return;
  76804. }
  76805. this._btnVR.className = "babylonVRicon";
  76806. if (this.isInVRMode) {
  76807. this._btnVR.className += " vrdisplaypresenting";
  76808. }
  76809. else {
  76810. if (this._webVRready)
  76811. this._btnVR.className += " vrdisplayready";
  76812. if (this._webVRsupported)
  76813. this._btnVR.className += " vrdisplaysupported";
  76814. if (this._webVRrequesting)
  76815. this._btnVR.className += " vrdisplayrequesting";
  76816. }
  76817. };
  76818. /**
  76819. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  76820. * Otherwise, will use the fullscreen API.
  76821. */
  76822. VRExperienceHelper.prototype.enterVR = function () {
  76823. if (this.onEnteringVRObservable) {
  76824. try {
  76825. this.onEnteringVRObservable.notifyObservers(this);
  76826. }
  76827. catch (err) {
  76828. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  76829. }
  76830. }
  76831. if (this._scene.activeCamera) {
  76832. this._position = this._scene.activeCamera.position.clone();
  76833. // make sure that we return to the last active camera
  76834. this._existingCamera = this._scene.activeCamera;
  76835. }
  76836. if (this._webVRrequesting)
  76837. return;
  76838. // If WebVR is supported and a headset is connected
  76839. if (this._webVRready) {
  76840. if (!this._webVRpresenting) {
  76841. this._webVRCamera.position = this._position;
  76842. this._scene.activeCamera = this._webVRCamera;
  76843. }
  76844. }
  76845. else if (this._vrDeviceOrientationCamera) {
  76846. this._vrDeviceOrientationCamera.position = this._position;
  76847. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  76848. this._scene.getEngine().switchFullscreen(true);
  76849. this.updateButtonVisibility();
  76850. }
  76851. if (this._scene.activeCamera && this._canvas) {
  76852. this._scene.activeCamera.attachControl(this._canvas);
  76853. }
  76854. if (this._interactionsEnabled) {
  76855. this._scene.registerBeforeRender(this.beforeRender);
  76856. }
  76857. };
  76858. /**
  76859. * Attempt to exit VR, or fullscreen.
  76860. */
  76861. VRExperienceHelper.prototype.exitVR = function () {
  76862. if (this.onExitingVRObservable) {
  76863. try {
  76864. this.onExitingVRObservable.notifyObservers(this);
  76865. }
  76866. catch (err) {
  76867. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  76868. }
  76869. }
  76870. if (this._webVRpresenting) {
  76871. this._scene.getEngine().disableVR();
  76872. }
  76873. if (this._scene.activeCamera) {
  76874. this._position = this._scene.activeCamera.position.clone();
  76875. }
  76876. if (this._deviceOrientationCamera) {
  76877. this._deviceOrientationCamera.position = this._position;
  76878. this._scene.activeCamera = this._deviceOrientationCamera;
  76879. if (this._canvas) {
  76880. this._scene.activeCamera.attachControl(this._canvas);
  76881. }
  76882. }
  76883. else if (this._existingCamera) {
  76884. this._existingCamera.position = this._position;
  76885. this._scene.activeCamera = this._existingCamera;
  76886. }
  76887. this.updateButtonVisibility();
  76888. if (this._interactionsEnabled) {
  76889. this._scene.unregisterBeforeRender(this.beforeRender);
  76890. }
  76891. };
  76892. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  76893. /**
  76894. * The position of the vr experience helper.
  76895. */
  76896. get: function () {
  76897. return this._position;
  76898. },
  76899. /**
  76900. * Sets the position of the vr experience helper.
  76901. */
  76902. set: function (value) {
  76903. this._position = value;
  76904. if (this._scene.activeCamera) {
  76905. this._scene.activeCamera.position = value;
  76906. }
  76907. },
  76908. enumerable: true,
  76909. configurable: true
  76910. });
  76911. /**
  76912. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  76913. */
  76914. VRExperienceHelper.prototype.enableInteractions = function () {
  76915. var _this = this;
  76916. if (!this._interactionsEnabled) {
  76917. this._interactionsRequested = true;
  76918. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76919. this._enableInteractionOnController(this._webVRCamera.leftController);
  76920. }
  76921. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76922. this._enableInteractionOnController(this._webVRCamera.rightController);
  76923. }
  76924. this._createGazeTracker();
  76925. this.raySelectionPredicate = function (mesh) {
  76926. return mesh.isVisible;
  76927. };
  76928. this.meshSelectionPredicate = function (mesh) {
  76929. return true;
  76930. };
  76931. this._raySelectionPredicate = function (mesh) {
  76932. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  76933. && mesh.name.indexOf("teleportationTarget") === -1
  76934. && mesh.name.indexOf("torusTeleportation") === -1
  76935. && mesh.name.indexOf("laserPointer") === -1)) {
  76936. return _this.raySelectionPredicate(mesh);
  76937. }
  76938. return false;
  76939. };
  76940. this._interactionsEnabled = true;
  76941. }
  76942. };
  76943. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  76944. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  76945. if (this._floorMeshesCollection[i].id === mesh.id) {
  76946. return true;
  76947. }
  76948. }
  76949. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  76950. return true;
  76951. }
  76952. return false;
  76953. };
  76954. /**
  76955. * Adds a floor mesh to be used for teleportation.
  76956. * @param floorMesh the mesh to be used for teleportation.
  76957. */
  76958. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  76959. if (!this._floorMeshesCollection) {
  76960. return;
  76961. }
  76962. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  76963. return;
  76964. }
  76965. this._floorMeshesCollection.push(floorMesh);
  76966. };
  76967. /**
  76968. * Removes a floor mesh from being used for teleportation.
  76969. * @param floorMesh the mesh to be removed.
  76970. */
  76971. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  76972. if (!this._floorMeshesCollection) {
  76973. return;
  76974. }
  76975. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  76976. if (meshIndex !== -1) {
  76977. this._floorMeshesCollection.splice(meshIndex, 1);
  76978. }
  76979. };
  76980. /**
  76981. * Enables interactions and teleportation using the VR controllers and gaze.
  76982. * @param vrTeleportationOptions options to modify teleportation behavior.
  76983. */
  76984. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  76985. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  76986. if (!this._teleportationInitialized) {
  76987. this._teleportationRequested = true;
  76988. this.enableInteractions();
  76989. if (vrTeleportationOptions.floorMeshName) {
  76990. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  76991. }
  76992. if (vrTeleportationOptions.floorMeshes) {
  76993. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  76994. }
  76995. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76996. this._enableTeleportationOnController(this._webVRCamera.leftController);
  76997. }
  76998. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76999. this._enableTeleportationOnController(this._webVRCamera.rightController);
  77000. }
  77001. // Creates an image processing post process for the vignette not relying
  77002. // on the main scene configuration for image processing to reduce setup and spaces
  77003. // (gamma/linear) conflicts.
  77004. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  77005. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77006. imageProcessingConfiguration.vignetteEnabled = true;
  77007. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  77008. this._webVRCamera.detachPostProcess(this._postProcessMove);
  77009. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  77010. this._teleportationInitialized = true;
  77011. if (this._isDefaultTeleportationTarget) {
  77012. this._createTeleportationCircles();
  77013. }
  77014. }
  77015. };
  77016. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  77017. var _this = this;
  77018. var controllerMesh = webVRController.mesh;
  77019. if (controllerMesh) {
  77020. var makeNotPick = function (root) {
  77021. root.name += " laserPointer";
  77022. root.getChildMeshes().forEach(function (c) {
  77023. makeNotPick(c);
  77024. });
  77025. };
  77026. makeNotPick(controllerMesh);
  77027. var childMeshes = controllerMesh.getChildMeshes();
  77028. for (var i = 0; i < childMeshes.length; i++) {
  77029. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  77030. controllerMesh = childMeshes[i];
  77031. break;
  77032. }
  77033. }
  77034. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  77035. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  77036. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77037. laserPointerMaterial.alpha = 0.6;
  77038. laserPointer.material = laserPointerMaterial;
  77039. laserPointer.rotation.x = Math.PI / 2;
  77040. laserPointer.parent = controllerMesh;
  77041. laserPointer.position.z = -0.5;
  77042. laserPointer.isVisible = false;
  77043. if (webVRController.hand === "left") {
  77044. this._leftLaserPointer = laserPointer;
  77045. this._interactionsEnabledOnLeftController = true;
  77046. if (!this._rightLaserPointer) {
  77047. this._leftLaserPointer.isVisible = true;
  77048. }
  77049. }
  77050. else {
  77051. this._rightLaserPointer = laserPointer;
  77052. this._interactionsEnabledOnRightController = true;
  77053. if (!this._leftLaserPointer) {
  77054. this._rightLaserPointer.isVisible = true;
  77055. }
  77056. }
  77057. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  77058. // Enabling / disabling laserPointer
  77059. if (_this._displayLaserPointer && stateObject.value === 1) {
  77060. laserPointer.isVisible = !laserPointer.isVisible;
  77061. // Laser pointer can only be active on left or right, not both at the same time
  77062. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  77063. _this._rightLaserPointer.isVisible = false;
  77064. }
  77065. else if (_this._leftLaserPointer) {
  77066. _this._leftLaserPointer.isVisible = false;
  77067. }
  77068. }
  77069. });
  77070. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  77071. if (!_this._pointerDownOnMeshAsked) {
  77072. if (stateObject.value > _this._padSensibilityUp) {
  77073. _this._selectionPointerDown();
  77074. }
  77075. }
  77076. else if (stateObject.value < _this._padSensibilityDown) {
  77077. _this._selectionPointerUp();
  77078. }
  77079. });
  77080. }
  77081. };
  77082. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  77083. if (webVRController === void 0) { webVRController = null; }
  77084. if (!this._teleportationRequestInitiated) {
  77085. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  77086. if (webVRController) {
  77087. // If laser pointer wasn't enabled yet
  77088. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  77089. this._leftLaserPointer.isVisible = true;
  77090. if (this._rightLaserPointer) {
  77091. this._rightLaserPointer.isVisible = false;
  77092. }
  77093. }
  77094. else if (this._displayLaserPointer && this._rightLaserPointer) {
  77095. this._rightLaserPointer.isVisible = true;
  77096. if (this._leftLaserPointer) {
  77097. this._leftLaserPointer.isVisible = false;
  77098. }
  77099. }
  77100. }
  77101. this._teleportationRequestInitiated = true;
  77102. }
  77103. }
  77104. else {
  77105. // Listening to the proper controller values changes to confirm teleportation
  77106. if (webVRController == null
  77107. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  77108. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  77109. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  77110. if (this._teleportationAllowed) {
  77111. this._teleportationAllowed = false;
  77112. this._teleportCamera();
  77113. }
  77114. this._teleportationRequestInitiated = false;
  77115. }
  77116. }
  77117. }
  77118. };
  77119. VRExperienceHelper.prototype._selectionPointerDown = function () {
  77120. this._pointerDownOnMeshAsked = true;
  77121. if (this._currentMeshSelected && this._currentHit) {
  77122. this._scene.simulatePointerDown(this._currentHit);
  77123. }
  77124. };
  77125. VRExperienceHelper.prototype._selectionPointerUp = function () {
  77126. if (this._currentMeshSelected && this._currentHit) {
  77127. this._scene.simulatePointerUp(this._currentHit);
  77128. }
  77129. this._pointerDownOnMeshAsked = false;
  77130. };
  77131. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  77132. // Only rotate when user is not currently selecting a teleportation location
  77133. if (this._teleportationRequestInitiated) {
  77134. return;
  77135. }
  77136. if (!this._rotationLeftAsked) {
  77137. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  77138. this._rotationLeftAsked = true;
  77139. if (this._rotationAllowed) {
  77140. this._rotateCamera(false);
  77141. }
  77142. }
  77143. }
  77144. else {
  77145. if (stateObject.x > -this._padSensibilityDown) {
  77146. this._rotationLeftAsked = false;
  77147. }
  77148. }
  77149. if (!this._rotationRightAsked) {
  77150. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  77151. this._rotationRightAsked = true;
  77152. if (this._rotationAllowed) {
  77153. this._rotateCamera(true);
  77154. }
  77155. }
  77156. }
  77157. else {
  77158. if (stateObject.x < this._padSensibilityDown) {
  77159. this._rotationRightAsked = false;
  77160. }
  77161. }
  77162. };
  77163. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  77164. // Only teleport backwards when user is not currently selecting a teleportation location
  77165. if (this._teleportationRequestInitiated) {
  77166. return;
  77167. }
  77168. // Teleport backwards
  77169. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  77170. if (!this._teleportationBackRequestInitiated) {
  77171. if (!this.currentVRCamera) {
  77172. return;
  77173. }
  77174. // Get rotation and position of the current camera
  77175. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  77176. var position = this.currentVRCamera.position;
  77177. // If the camera has device position, use that instead
  77178. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  77179. rotation = this.currentVRCamera.deviceRotationQuaternion;
  77180. position = this.currentVRCamera.devicePosition;
  77181. }
  77182. // Get matrix with only the y rotation of the device rotation
  77183. rotation.toEulerAnglesToRef(this._workingVector);
  77184. this._workingVector.z = 0;
  77185. this._workingVector.x = 0;
  77186. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  77187. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  77188. // Rotate backwards ray by device rotation to cast at the ground behind the user
  77189. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  77190. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  77191. var ray = new BABYLON.Ray(position, this._workingVector);
  77192. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77193. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  77194. this._teleportCamera(hit.pickedPoint);
  77195. }
  77196. this._teleportationBackRequestInitiated = true;
  77197. }
  77198. }
  77199. else {
  77200. this._teleportationBackRequestInitiated = false;
  77201. }
  77202. };
  77203. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  77204. var _this = this;
  77205. var controllerMesh = webVRController.mesh;
  77206. if (controllerMesh) {
  77207. if (webVRController.hand === "left") {
  77208. if (!this._interactionsEnabledOnLeftController) {
  77209. this._enableInteractionOnController(webVRController);
  77210. }
  77211. this._teleportationEnabledOnLeftController = true;
  77212. }
  77213. else {
  77214. if (!this._interactionsEnabledOnRightController) {
  77215. this._enableInteractionOnController(webVRController);
  77216. }
  77217. this._teleportationEnabledOnRightController = true;
  77218. }
  77219. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77220. this._dpadPressed = false;
  77221. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  77222. _this._dpadPressed = stateObject.pressed;
  77223. if (!_this._dpadPressed) {
  77224. _this._rotationLeftAsked = false;
  77225. _this._rotationRightAsked = false;
  77226. _this._teleportationBackRequestInitiated = false;
  77227. }
  77228. });
  77229. }
  77230. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  77231. if (_this.teleportationEnabled) {
  77232. _this._checkTeleportBackwards(stateObject);
  77233. _this._checkTeleportWithRay(stateObject, webVRController);
  77234. }
  77235. _this._checkRotate(stateObject);
  77236. });
  77237. }
  77238. };
  77239. // Gaze support used to point to teleport or to interact with an object
  77240. VRExperienceHelper.prototype._createGazeTracker = function () {
  77241. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  77242. this._gazeTracker.bakeCurrentTransformIntoVertices();
  77243. this._gazeTracker.isPickable = false;
  77244. this._gazeTracker.isVisible = false;
  77245. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  77246. targetMat.specularColor = BABYLON.Color3.Black();
  77247. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77248. targetMat.backFaceCulling = false;
  77249. this._gazeTracker.material = targetMat;
  77250. };
  77251. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  77252. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  77253. this._teleportationTarget.isPickable = false;
  77254. var length = 512;
  77255. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  77256. dynamicTexture.hasAlpha = true;
  77257. var context = dynamicTexture.getContext();
  77258. var centerX = length / 2;
  77259. var centerY = length / 2;
  77260. var radius = 200;
  77261. context.beginPath();
  77262. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  77263. context.fillStyle = this._teleportationFillColor;
  77264. context.fill();
  77265. context.lineWidth = 10;
  77266. context.strokeStyle = this._teleportationBorderColor;
  77267. context.stroke();
  77268. context.closePath();
  77269. dynamicTexture.update();
  77270. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  77271. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  77272. this._teleportationTarget.material = teleportationCircleMaterial;
  77273. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  77274. torus.isPickable = false;
  77275. torus.parent = this._teleportationTarget;
  77276. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77277. var keys = [];
  77278. keys.push({
  77279. frame: 0,
  77280. value: 0
  77281. });
  77282. keys.push({
  77283. frame: 30,
  77284. value: 0.4
  77285. });
  77286. keys.push({
  77287. frame: 60,
  77288. value: 0
  77289. });
  77290. animationInnerCircle.setKeys(keys);
  77291. var easingFunction = new BABYLON.SineEase();
  77292. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77293. animationInnerCircle.setEasingFunction(easingFunction);
  77294. torus.animations = [];
  77295. torus.animations.push(animationInnerCircle);
  77296. this._scene.beginAnimation(torus, 0, 60, true);
  77297. this._hideTeleportationTarget();
  77298. };
  77299. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  77300. if (this._teleportationInitialized) {
  77301. this._teleportationTarget.isVisible = true;
  77302. if (this._isDefaultTeleportationTarget) {
  77303. this._teleportationTarget.getChildren()[0].isVisible = true;
  77304. }
  77305. }
  77306. };
  77307. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  77308. if (this._teleportationInitialized) {
  77309. this._teleportationTarget.isVisible = false;
  77310. if (this._isDefaultTeleportationTarget) {
  77311. this._teleportationTarget.getChildren()[0].isVisible = false;
  77312. }
  77313. }
  77314. };
  77315. VRExperienceHelper.prototype._rotateCamera = function (right) {
  77316. var _this = this;
  77317. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77318. return;
  77319. }
  77320. if (right) {
  77321. this._rotationAngle++;
  77322. }
  77323. else {
  77324. this._rotationAngle--;
  77325. }
  77326. this.currentVRCamera.animations = [];
  77327. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  77328. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77329. var animationRotationKeys = [];
  77330. animationRotationKeys.push({
  77331. frame: 0,
  77332. value: this.currentVRCamera.rotationQuaternion
  77333. });
  77334. animationRotationKeys.push({
  77335. frame: 6,
  77336. value: target
  77337. });
  77338. animationRotation.setKeys(animationRotationKeys);
  77339. animationRotation.setEasingFunction(this._circleEase);
  77340. this.currentVRCamera.animations.push(animationRotation);
  77341. this._postProcessMove.animations = [];
  77342. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77343. var vignetteWeightKeys = [];
  77344. vignetteWeightKeys.push({
  77345. frame: 0,
  77346. value: 0
  77347. });
  77348. vignetteWeightKeys.push({
  77349. frame: 3,
  77350. value: 4
  77351. });
  77352. vignetteWeightKeys.push({
  77353. frame: 6,
  77354. value: 0
  77355. });
  77356. animationPP.setKeys(vignetteWeightKeys);
  77357. animationPP.setEasingFunction(this._circleEase);
  77358. this._postProcessMove.animations.push(animationPP);
  77359. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77360. var vignetteStretchKeys = [];
  77361. vignetteStretchKeys.push({
  77362. frame: 0,
  77363. value: 0
  77364. });
  77365. vignetteStretchKeys.push({
  77366. frame: 3,
  77367. value: 10
  77368. });
  77369. vignetteStretchKeys.push({
  77370. frame: 6,
  77371. value: 0
  77372. });
  77373. animationPP2.setKeys(vignetteStretchKeys);
  77374. animationPP2.setEasingFunction(this._circleEase);
  77375. this._postProcessMove.animations.push(animationPP2);
  77376. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77377. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77378. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77379. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  77380. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77381. });
  77382. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  77383. };
  77384. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  77385. if (hit.pickedPoint) {
  77386. this._teleportationAllowed = true;
  77387. if (this._teleportationRequestInitiated) {
  77388. this._displayTeleportationTarget();
  77389. }
  77390. else {
  77391. this._hideTeleportationTarget();
  77392. }
  77393. this._haloCenter.copyFrom(hit.pickedPoint);
  77394. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  77395. var pickNormal = hit.getNormal(true, false);
  77396. if (pickNormal) {
  77397. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77398. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77399. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  77400. }
  77401. this._teleportationTarget.position.y += 0.1;
  77402. }
  77403. };
  77404. VRExperienceHelper.prototype._teleportCamera = function (location) {
  77405. var _this = this;
  77406. if (location === void 0) { location = null; }
  77407. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77408. return;
  77409. }
  77410. if (!location) {
  77411. location = this._haloCenter;
  77412. }
  77413. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  77414. // offset of the headset from the anchor.
  77415. if (this.webVRCamera.leftCamera) {
  77416. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  77417. this._workingVector.subtractInPlace(this.webVRCamera.position);
  77418. location.subtractToRef(this._workingVector, this._workingVector);
  77419. }
  77420. else {
  77421. this._workingVector.copyFrom(location);
  77422. }
  77423. // Add height to account for user's height offset
  77424. if (this.isInVRMode) {
  77425. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  77426. }
  77427. else {
  77428. this._workingVector.y += this._defaultHeight;
  77429. }
  77430. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  77431. // Create animation from the camera's position to the new location
  77432. this.currentVRCamera.animations = [];
  77433. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77434. var animationCameraTeleportationKeys = [{
  77435. frame: 0,
  77436. value: this.currentVRCamera.position
  77437. },
  77438. {
  77439. frame: 11,
  77440. value: this._workingVector
  77441. }
  77442. ];
  77443. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  77444. animationCameraTeleportation.setEasingFunction(this._circleEase);
  77445. this.currentVRCamera.animations.push(animationCameraTeleportation);
  77446. this._postProcessMove.animations = [];
  77447. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77448. var vignetteWeightKeys = [];
  77449. vignetteWeightKeys.push({
  77450. frame: 0,
  77451. value: 0
  77452. });
  77453. vignetteWeightKeys.push({
  77454. frame: 5,
  77455. value: 8
  77456. });
  77457. vignetteWeightKeys.push({
  77458. frame: 11,
  77459. value: 0
  77460. });
  77461. animationPP.setKeys(vignetteWeightKeys);
  77462. this._postProcessMove.animations.push(animationPP);
  77463. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77464. var vignetteStretchKeys = [];
  77465. vignetteStretchKeys.push({
  77466. frame: 0,
  77467. value: 0
  77468. });
  77469. vignetteStretchKeys.push({
  77470. frame: 5,
  77471. value: 10
  77472. });
  77473. vignetteStretchKeys.push({
  77474. frame: 11,
  77475. value: 0
  77476. });
  77477. animationPP2.setKeys(vignetteStretchKeys);
  77478. this._postProcessMove.animations.push(animationPP2);
  77479. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77480. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77481. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77482. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  77483. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77484. });
  77485. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  77486. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  77487. });
  77488. };
  77489. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  77490. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77491. return;
  77492. }
  77493. var ray;
  77494. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  77495. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  77496. }
  77497. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  77498. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  77499. }
  77500. else {
  77501. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  77502. }
  77503. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77504. // Moving the gazeTracker on the mesh face targetted
  77505. if (hit && hit.pickedPoint) {
  77506. if (this._displayGaze) {
  77507. var multiplier = 1;
  77508. this._gazeTracker.isVisible = true;
  77509. if (this._isActionableMesh) {
  77510. multiplier = 3;
  77511. }
  77512. this._gazeTracker.scaling.x = hit.distance * multiplier;
  77513. this._gazeTracker.scaling.y = hit.distance * multiplier;
  77514. this._gazeTracker.scaling.z = hit.distance * multiplier;
  77515. var pickNormal = hit.getNormal();
  77516. // To avoid z-fighting
  77517. var deltaFighting = 0.002;
  77518. if (pickNormal) {
  77519. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77520. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77521. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  77522. }
  77523. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  77524. if (this._gazeTracker.position.x < 0) {
  77525. this._gazeTracker.position.x += deltaFighting;
  77526. }
  77527. else {
  77528. this._gazeTracker.position.x -= deltaFighting;
  77529. }
  77530. if (this._gazeTracker.position.y < 0) {
  77531. this._gazeTracker.position.y += deltaFighting;
  77532. }
  77533. else {
  77534. this._gazeTracker.position.y -= deltaFighting;
  77535. }
  77536. if (this._gazeTracker.position.z < 0) {
  77537. this._gazeTracker.position.z += deltaFighting;
  77538. }
  77539. else {
  77540. this._gazeTracker.position.z -= deltaFighting;
  77541. }
  77542. }
  77543. // Changing the size of the laser pointer based on the distance from the targetted point
  77544. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  77545. this._rightLaserPointer.scaling.y = hit.distance;
  77546. this._rightLaserPointer.position.z = -hit.distance / 2;
  77547. }
  77548. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  77549. this._leftLaserPointer.scaling.y = hit.distance;
  77550. this._leftLaserPointer.position.z = -hit.distance / 2;
  77551. }
  77552. }
  77553. else {
  77554. this._gazeTracker.isVisible = false;
  77555. }
  77556. if (hit && hit.pickedMesh) {
  77557. this._currentHit = hit;
  77558. if (this._pointerDownOnMeshAsked) {
  77559. this._scene.simulatePointerMove(this._currentHit);
  77560. }
  77561. // The object selected is the floor, we're in a teleportation scenario
  77562. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  77563. // Moving the teleportation area to this targetted point
  77564. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  77565. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  77566. this._notifySelectedMeshUnselected();
  77567. }
  77568. this._currentMeshSelected = null;
  77569. this._moveTeleportationSelectorTo(hit);
  77570. return;
  77571. }
  77572. // If not, we're in a selection scenario
  77573. this._hideTeleportationTarget();
  77574. this._teleportationAllowed = false;
  77575. if (hit.pickedMesh !== this._currentMeshSelected) {
  77576. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  77577. this.onNewMeshPicked.notifyObservers(hit);
  77578. this._currentMeshSelected = hit.pickedMesh;
  77579. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  77580. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  77581. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  77582. this._isActionableMesh = true;
  77583. }
  77584. else {
  77585. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77586. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77587. this._isActionableMesh = false;
  77588. }
  77589. try {
  77590. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  77591. }
  77592. catch (err) {
  77593. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  77594. }
  77595. }
  77596. else {
  77597. this._notifySelectedMeshUnselected();
  77598. this._currentMeshSelected = null;
  77599. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77600. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77601. }
  77602. }
  77603. }
  77604. else {
  77605. this._currentHit = null;
  77606. this._notifySelectedMeshUnselected();
  77607. this._currentMeshSelected = null;
  77608. this._teleportationAllowed = false;
  77609. this._hideTeleportationTarget();
  77610. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77611. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77612. }
  77613. };
  77614. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  77615. if (this._currentMeshSelected) {
  77616. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  77617. }
  77618. };
  77619. /**
  77620. * Sets the color of the laser ray from the vr controllers.
  77621. * @param color new color for the ray.
  77622. */
  77623. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  77624. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  77625. this._leftLaserPointer.material.emissiveColor = color;
  77626. }
  77627. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  77628. this._rightLaserPointer.material.emissiveColor = color;
  77629. }
  77630. };
  77631. /**
  77632. * Sets the color of the ray from the vr headsets gaze.
  77633. * @param color new color for the ray.
  77634. */
  77635. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  77636. if (this._gazeTracker.material) {
  77637. this._gazeTracker.material.emissiveColor = color;
  77638. }
  77639. };
  77640. /**
  77641. * Exits VR and disposes of the vr experience helper
  77642. */
  77643. VRExperienceHelper.prototype.dispose = function () {
  77644. if (this.isInVRMode) {
  77645. this.exitVR();
  77646. }
  77647. if (this._passProcessMove) {
  77648. this._passProcessMove.dispose();
  77649. }
  77650. if (this._postProcessMove) {
  77651. this._postProcessMove.dispose();
  77652. }
  77653. if (this._webVRCamera) {
  77654. this._webVRCamera.dispose();
  77655. }
  77656. if (this._vrDeviceOrientationCamera) {
  77657. this._vrDeviceOrientationCamera.dispose();
  77658. }
  77659. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  77660. document.body.removeChild(this._btnVR);
  77661. }
  77662. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  77663. this._deviceOrientationCamera.dispose();
  77664. }
  77665. if (this._gazeTracker) {
  77666. this._gazeTracker.dispose();
  77667. }
  77668. if (this._teleportationTarget) {
  77669. this._teleportationTarget.dispose();
  77670. }
  77671. this._floorMeshesCollection = [];
  77672. document.removeEventListener("keydown", this._onKeyDown);
  77673. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77674. window.removeEventListener("resize", this._onResize);
  77675. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  77676. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  77677. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  77678. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  77679. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  77680. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  77681. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  77682. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77683. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  77684. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  77685. this._scene.unregisterBeforeRender(this.beforeRender);
  77686. };
  77687. /**
  77688. * Gets the name of the VRExperienceHelper class
  77689. * @returns "VRExperienceHelper"
  77690. */
  77691. VRExperienceHelper.prototype.getClassName = function () {
  77692. return "VRExperienceHelper";
  77693. };
  77694. return VRExperienceHelper;
  77695. }());
  77696. BABYLON.VRExperienceHelper = VRExperienceHelper;
  77697. })(BABYLON || (BABYLON = {}));
  77698. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  77699. // Mainly based on these 2 articles :
  77700. // 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
  77701. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  77702. var BABYLON;
  77703. (function (BABYLON) {
  77704. var JoystickAxis;
  77705. (function (JoystickAxis) {
  77706. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  77707. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  77708. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  77709. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  77710. var VirtualJoystick = /** @class */ (function () {
  77711. function VirtualJoystick(leftJoystick) {
  77712. var _this = this;
  77713. if (leftJoystick) {
  77714. this._leftJoystick = true;
  77715. }
  77716. else {
  77717. this._leftJoystick = false;
  77718. }
  77719. VirtualJoystick._globalJoystickIndex++;
  77720. // By default left & right arrow keys are moving the X
  77721. // and up & down keys are moving the Y
  77722. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77723. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77724. this.reverseLeftRight = false;
  77725. this.reverseUpDown = false;
  77726. // collections of pointers
  77727. this._touches = new BABYLON.StringDictionary();
  77728. this.deltaPosition = BABYLON.Vector3.Zero();
  77729. this._joystickSensibility = 25;
  77730. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77731. this._onResize = function (evt) {
  77732. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77733. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77734. if (VirtualJoystick.vjCanvas) {
  77735. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  77736. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  77737. }
  77738. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  77739. };
  77740. // injecting a canvas element on top of the canvas 3D game
  77741. if (!VirtualJoystick.vjCanvas) {
  77742. window.addEventListener("resize", this._onResize, false);
  77743. VirtualJoystick.vjCanvas = document.createElement("canvas");
  77744. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77745. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77746. VirtualJoystick.vjCanvas.width = window.innerWidth;
  77747. VirtualJoystick.vjCanvas.height = window.innerHeight;
  77748. VirtualJoystick.vjCanvas.style.width = "100%";
  77749. VirtualJoystick.vjCanvas.style.height = "100%";
  77750. VirtualJoystick.vjCanvas.style.position = "absolute";
  77751. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  77752. VirtualJoystick.vjCanvas.style.top = "0px";
  77753. VirtualJoystick.vjCanvas.style.left = "0px";
  77754. VirtualJoystick.vjCanvas.style.zIndex = "5";
  77755. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  77756. // Support for jQuery PEP polyfill
  77757. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  77758. var context = VirtualJoystick.vjCanvas.getContext('2d');
  77759. if (!context) {
  77760. throw new Error("Unable to create canvas for virtual joystick");
  77761. }
  77762. VirtualJoystick.vjCanvasContext = context;
  77763. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  77764. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77765. document.body.appendChild(VirtualJoystick.vjCanvas);
  77766. }
  77767. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  77768. this.pressed = false;
  77769. // default joystick color
  77770. this._joystickColor = "cyan";
  77771. this._joystickPointerID = -1;
  77772. // current joystick position
  77773. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  77774. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  77775. // origin joystick position
  77776. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  77777. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  77778. this._onPointerDownHandlerRef = function (evt) {
  77779. _this._onPointerDown(evt);
  77780. };
  77781. this._onPointerMoveHandlerRef = function (evt) {
  77782. _this._onPointerMove(evt);
  77783. };
  77784. this._onPointerUpHandlerRef = function (evt) {
  77785. _this._onPointerUp(evt);
  77786. };
  77787. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  77788. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  77789. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  77790. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  77791. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  77792. evt.preventDefault(); // Disables system menu
  77793. }, false);
  77794. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77795. }
  77796. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  77797. this._joystickSensibility = newJoystickSensibility;
  77798. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77799. };
  77800. VirtualJoystick.prototype._onPointerDown = function (e) {
  77801. var positionOnScreenCondition;
  77802. e.preventDefault();
  77803. if (this._leftJoystick === true) {
  77804. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  77805. }
  77806. else {
  77807. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  77808. }
  77809. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  77810. // First contact will be dedicated to the virtual joystick
  77811. this._joystickPointerID = e.pointerId;
  77812. this._joystickPointerStartPos.x = e.clientX;
  77813. this._joystickPointerStartPos.y = e.clientY;
  77814. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  77815. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  77816. this._deltaJoystickVector.x = 0;
  77817. this._deltaJoystickVector.y = 0;
  77818. this.pressed = true;
  77819. this._touches.add(e.pointerId.toString(), e);
  77820. }
  77821. else {
  77822. // You can only trigger the action buttons with a joystick declared
  77823. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  77824. this._action();
  77825. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  77826. }
  77827. }
  77828. };
  77829. VirtualJoystick.prototype._onPointerMove = function (e) {
  77830. // If the current pointer is the one associated to the joystick (first touch contact)
  77831. if (this._joystickPointerID == e.pointerId) {
  77832. this._joystickPointerPos.x = e.clientX;
  77833. this._joystickPointerPos.y = e.clientY;
  77834. this._deltaJoystickVector = this._joystickPointerPos.clone();
  77835. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  77836. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  77837. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  77838. switch (this._axisTargetedByLeftAndRight) {
  77839. case JoystickAxis.X:
  77840. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  77841. break;
  77842. case JoystickAxis.Y:
  77843. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  77844. break;
  77845. case JoystickAxis.Z:
  77846. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  77847. break;
  77848. }
  77849. var directionUpDown = this.reverseUpDown ? 1 : -1;
  77850. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  77851. switch (this._axisTargetedByUpAndDown) {
  77852. case JoystickAxis.X:
  77853. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  77854. break;
  77855. case JoystickAxis.Y:
  77856. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  77857. break;
  77858. case JoystickAxis.Z:
  77859. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  77860. break;
  77861. }
  77862. }
  77863. else {
  77864. var data = this._touches.get(e.pointerId.toString());
  77865. if (data) {
  77866. data.x = e.clientX;
  77867. data.y = e.clientY;
  77868. }
  77869. }
  77870. };
  77871. VirtualJoystick.prototype._onPointerUp = function (e) {
  77872. if (this._joystickPointerID == e.pointerId) {
  77873. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  77874. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  77875. this._joystickPointerID = -1;
  77876. this.pressed = false;
  77877. }
  77878. else {
  77879. var touch = this._touches.get(e.pointerId.toString());
  77880. if (touch) {
  77881. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77882. }
  77883. }
  77884. this._deltaJoystickVector.x = 0;
  77885. this._deltaJoystickVector.y = 0;
  77886. this._touches.remove(e.pointerId.toString());
  77887. };
  77888. /**
  77889. * Change the color of the virtual joystick
  77890. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  77891. */
  77892. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  77893. this._joystickColor = newColor;
  77894. };
  77895. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  77896. this._action = action;
  77897. };
  77898. // Define which axis you'd like to control for left & right
  77899. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  77900. switch (axis) {
  77901. case JoystickAxis.X:
  77902. case JoystickAxis.Y:
  77903. case JoystickAxis.Z:
  77904. this._axisTargetedByLeftAndRight = axis;
  77905. break;
  77906. default:
  77907. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77908. break;
  77909. }
  77910. };
  77911. // Define which axis you'd like to control for up & down
  77912. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  77913. switch (axis) {
  77914. case JoystickAxis.X:
  77915. case JoystickAxis.Y:
  77916. case JoystickAxis.Z:
  77917. this._axisTargetedByUpAndDown = axis;
  77918. break;
  77919. default:
  77920. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77921. break;
  77922. }
  77923. };
  77924. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  77925. var _this = this;
  77926. if (this.pressed) {
  77927. this._touches.forEach(function (key, touch) {
  77928. if (touch.pointerId === _this._joystickPointerID) {
  77929. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  77930. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  77931. VirtualJoystick.vjCanvasContext.beginPath();
  77932. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77933. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77934. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  77935. VirtualJoystick.vjCanvasContext.stroke();
  77936. VirtualJoystick.vjCanvasContext.closePath();
  77937. VirtualJoystick.vjCanvasContext.beginPath();
  77938. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77939. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77940. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  77941. VirtualJoystick.vjCanvasContext.stroke();
  77942. VirtualJoystick.vjCanvasContext.closePath();
  77943. VirtualJoystick.vjCanvasContext.beginPath();
  77944. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77945. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  77946. VirtualJoystick.vjCanvasContext.stroke();
  77947. VirtualJoystick.vjCanvasContext.closePath();
  77948. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  77949. }
  77950. else {
  77951. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77952. VirtualJoystick.vjCanvasContext.beginPath();
  77953. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  77954. VirtualJoystick.vjCanvasContext.beginPath();
  77955. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  77956. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77957. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  77958. VirtualJoystick.vjCanvasContext.stroke();
  77959. VirtualJoystick.vjCanvasContext.closePath();
  77960. touch.prevX = touch.x;
  77961. touch.prevY = touch.y;
  77962. }
  77963. ;
  77964. });
  77965. }
  77966. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77967. };
  77968. VirtualJoystick.prototype.releaseCanvas = function () {
  77969. if (VirtualJoystick.vjCanvas) {
  77970. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  77971. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  77972. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  77973. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  77974. window.removeEventListener("resize", this._onResize);
  77975. document.body.removeChild(VirtualJoystick.vjCanvas);
  77976. VirtualJoystick.vjCanvas = null;
  77977. }
  77978. };
  77979. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  77980. VirtualJoystick._globalJoystickIndex = 0;
  77981. return VirtualJoystick;
  77982. }());
  77983. BABYLON.VirtualJoystick = VirtualJoystick;
  77984. })(BABYLON || (BABYLON = {}));
  77985. //# sourceMappingURL=babylon.virtualJoystick.js.map
  77986. var BABYLON;
  77987. (function (BABYLON) {
  77988. // We're mainly based on the logic defined into the FreeCamera code
  77989. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  77990. __extends(VirtualJoysticksCamera, _super);
  77991. function VirtualJoysticksCamera(name, position, scene) {
  77992. var _this = _super.call(this, name, position, scene) || this;
  77993. _this.inputs.addVirtualJoystick();
  77994. return _this;
  77995. }
  77996. VirtualJoysticksCamera.prototype.getClassName = function () {
  77997. return "VirtualJoysticksCamera";
  77998. };
  77999. return VirtualJoysticksCamera;
  78000. }(BABYLON.FreeCamera));
  78001. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  78002. })(BABYLON || (BABYLON = {}));
  78003. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  78004. var BABYLON;
  78005. (function (BABYLON) {
  78006. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  78007. function FreeCameraVirtualJoystickInput() {
  78008. }
  78009. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  78010. return this._leftjoystick;
  78011. };
  78012. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  78013. return this._rightjoystick;
  78014. };
  78015. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  78016. if (this._leftjoystick) {
  78017. var camera = this.camera;
  78018. var speed = camera._computeLocalCameraSpeed() * 50;
  78019. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  78020. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  78021. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  78022. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  78023. if (!this._leftjoystick.pressed) {
  78024. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  78025. }
  78026. if (!this._rightjoystick.pressed) {
  78027. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  78028. }
  78029. }
  78030. };
  78031. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  78032. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  78033. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  78034. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  78035. this._leftjoystick.setJoystickSensibility(0.15);
  78036. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  78037. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  78038. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  78039. this._rightjoystick.reverseUpDown = true;
  78040. this._rightjoystick.setJoystickSensibility(0.05);
  78041. this._rightjoystick.setJoystickColor("yellow");
  78042. };
  78043. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  78044. this._leftjoystick.releaseCanvas();
  78045. this._rightjoystick.releaseCanvas();
  78046. };
  78047. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  78048. return "FreeCameraVirtualJoystickInput";
  78049. };
  78050. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  78051. return "virtualJoystick";
  78052. };
  78053. return FreeCameraVirtualJoystickInput;
  78054. }());
  78055. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  78056. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  78057. })(BABYLON || (BABYLON = {}));
  78058. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  78059. var BABYLON;
  78060. (function (BABYLON) {
  78061. var SimplificationSettings = /** @class */ (function () {
  78062. function SimplificationSettings(quality, distance, optimizeMesh) {
  78063. this.quality = quality;
  78064. this.distance = distance;
  78065. this.optimizeMesh = optimizeMesh;
  78066. }
  78067. return SimplificationSettings;
  78068. }());
  78069. BABYLON.SimplificationSettings = SimplificationSettings;
  78070. var SimplificationQueue = /** @class */ (function () {
  78071. function SimplificationQueue() {
  78072. this.running = false;
  78073. this._simplificationArray = [];
  78074. }
  78075. SimplificationQueue.prototype.addTask = function (task) {
  78076. this._simplificationArray.push(task);
  78077. };
  78078. SimplificationQueue.prototype.executeNext = function () {
  78079. var task = this._simplificationArray.pop();
  78080. if (task) {
  78081. this.running = true;
  78082. this.runSimplification(task);
  78083. }
  78084. else {
  78085. this.running = false;
  78086. }
  78087. };
  78088. SimplificationQueue.prototype.runSimplification = function (task) {
  78089. var _this = this;
  78090. if (task.parallelProcessing) {
  78091. //parallel simplifier
  78092. task.settings.forEach(function (setting) {
  78093. var simplifier = _this.getSimplifier(task);
  78094. simplifier.simplify(setting, function (newMesh) {
  78095. task.mesh.addLODLevel(setting.distance, newMesh);
  78096. newMesh.isVisible = true;
  78097. //check if it is the last
  78098. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  78099. //all done, run the success callback.
  78100. task.successCallback();
  78101. }
  78102. _this.executeNext();
  78103. });
  78104. });
  78105. }
  78106. else {
  78107. //single simplifier.
  78108. var simplifier = this.getSimplifier(task);
  78109. var runDecimation = function (setting, callback) {
  78110. simplifier.simplify(setting, function (newMesh) {
  78111. task.mesh.addLODLevel(setting.distance, newMesh);
  78112. newMesh.isVisible = true;
  78113. //run the next quality level
  78114. callback();
  78115. });
  78116. };
  78117. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  78118. runDecimation(task.settings[loop.index], function () {
  78119. loop.executeNext();
  78120. });
  78121. }, function () {
  78122. //execution ended, run the success callback.
  78123. if (task.successCallback) {
  78124. task.successCallback();
  78125. }
  78126. _this.executeNext();
  78127. });
  78128. }
  78129. };
  78130. SimplificationQueue.prototype.getSimplifier = function (task) {
  78131. switch (task.simplificationType) {
  78132. case SimplificationType.QUADRATIC:
  78133. default:
  78134. return new QuadraticErrorSimplification(task.mesh);
  78135. }
  78136. };
  78137. return SimplificationQueue;
  78138. }());
  78139. BABYLON.SimplificationQueue = SimplificationQueue;
  78140. /**
  78141. * The implemented types of simplification.
  78142. * At the moment only Quadratic Error Decimation is implemented.
  78143. */
  78144. var SimplificationType;
  78145. (function (SimplificationType) {
  78146. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  78147. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  78148. var DecimationTriangle = /** @class */ (function () {
  78149. function DecimationTriangle(vertices) {
  78150. this.vertices = vertices;
  78151. this.error = new Array(4);
  78152. this.deleted = false;
  78153. this.isDirty = false;
  78154. this.deletePending = false;
  78155. this.borderFactor = 0;
  78156. }
  78157. return DecimationTriangle;
  78158. }());
  78159. BABYLON.DecimationTriangle = DecimationTriangle;
  78160. var DecimationVertex = /** @class */ (function () {
  78161. function DecimationVertex(position, id) {
  78162. this.position = position;
  78163. this.id = id;
  78164. this.isBorder = true;
  78165. this.q = new QuadraticMatrix();
  78166. this.triangleCount = 0;
  78167. this.triangleStart = 0;
  78168. this.originalOffsets = [];
  78169. }
  78170. DecimationVertex.prototype.updatePosition = function (newPosition) {
  78171. this.position.copyFrom(newPosition);
  78172. };
  78173. return DecimationVertex;
  78174. }());
  78175. BABYLON.DecimationVertex = DecimationVertex;
  78176. var QuadraticMatrix = /** @class */ (function () {
  78177. function QuadraticMatrix(data) {
  78178. this.data = new Array(10);
  78179. for (var i = 0; i < 10; ++i) {
  78180. if (data && data[i]) {
  78181. this.data[i] = data[i];
  78182. }
  78183. else {
  78184. this.data[i] = 0;
  78185. }
  78186. }
  78187. }
  78188. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  78189. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  78190. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  78191. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  78192. return det;
  78193. };
  78194. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  78195. for (var i = 0; i < 10; ++i) {
  78196. this.data[i] += matrix.data[i];
  78197. }
  78198. };
  78199. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  78200. for (var i = 0; i < 10; ++i) {
  78201. this.data[i] += data[i];
  78202. }
  78203. };
  78204. QuadraticMatrix.prototype.add = function (matrix) {
  78205. var m = new QuadraticMatrix();
  78206. for (var i = 0; i < 10; ++i) {
  78207. m.data[i] = this.data[i] + matrix.data[i];
  78208. }
  78209. return m;
  78210. };
  78211. QuadraticMatrix.FromData = function (a, b, c, d) {
  78212. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78213. };
  78214. //returning an array to avoid garbage collection
  78215. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  78216. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  78217. };
  78218. return QuadraticMatrix;
  78219. }());
  78220. BABYLON.QuadraticMatrix = QuadraticMatrix;
  78221. var Reference = /** @class */ (function () {
  78222. function Reference(vertexId, triangleId) {
  78223. this.vertexId = vertexId;
  78224. this.triangleId = triangleId;
  78225. }
  78226. return Reference;
  78227. }());
  78228. BABYLON.Reference = Reference;
  78229. /**
  78230. * An implementation of the Quadratic Error simplification algorithm.
  78231. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  78232. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  78233. * @author RaananW
  78234. */
  78235. var QuadraticErrorSimplification = /** @class */ (function () {
  78236. function QuadraticErrorSimplification(_mesh) {
  78237. this._mesh = _mesh;
  78238. this.syncIterations = 5000;
  78239. this.aggressiveness = 7;
  78240. this.decimationIterations = 100;
  78241. this.boundingBoxEpsilon = BABYLON.Epsilon;
  78242. }
  78243. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  78244. var _this = this;
  78245. this.initDecimatedMesh();
  78246. //iterating through the submeshes array, one after the other.
  78247. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  78248. _this.initWithMesh(loop.index, function () {
  78249. _this.runDecimation(settings, loop.index, function () {
  78250. loop.executeNext();
  78251. });
  78252. }, settings.optimizeMesh);
  78253. }, function () {
  78254. setTimeout(function () {
  78255. successCallback(_this._reconstructedMesh);
  78256. }, 0);
  78257. });
  78258. };
  78259. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  78260. var _this = this;
  78261. var targetCount = ~~(this.triangles.length * settings.quality);
  78262. var deletedTriangles = 0;
  78263. var triangleCount = this.triangles.length;
  78264. var iterationFunction = function (iteration, callback) {
  78265. setTimeout(function () {
  78266. if (iteration % 5 === 0) {
  78267. _this.updateMesh(iteration === 0);
  78268. }
  78269. for (var i = 0; i < _this.triangles.length; ++i) {
  78270. _this.triangles[i].isDirty = false;
  78271. }
  78272. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  78273. var trianglesIterator = function (i) {
  78274. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  78275. var t = _this.triangles[tIdx];
  78276. if (!t)
  78277. return;
  78278. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  78279. return;
  78280. }
  78281. for (var j = 0; j < 3; ++j) {
  78282. if (t.error[j] < threshold) {
  78283. var deleted0 = [];
  78284. var deleted1 = [];
  78285. var v0 = t.vertices[j];
  78286. var v1 = t.vertices[(j + 1) % 3];
  78287. if (v0.isBorder || v1.isBorder)
  78288. continue;
  78289. var p = BABYLON.Vector3.Zero();
  78290. var n = BABYLON.Vector3.Zero();
  78291. var uv = BABYLON.Vector2.Zero();
  78292. var color = new BABYLON.Color4(0, 0, 0, 1);
  78293. _this.calculateError(v0, v1, p, n, uv, color);
  78294. var delTr = new Array();
  78295. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  78296. continue;
  78297. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  78298. continue;
  78299. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  78300. continue;
  78301. var uniqueArray = new Array();
  78302. delTr.forEach(function (deletedT) {
  78303. if (uniqueArray.indexOf(deletedT) === -1) {
  78304. deletedT.deletePending = true;
  78305. uniqueArray.push(deletedT);
  78306. }
  78307. });
  78308. if (uniqueArray.length % 2 !== 0) {
  78309. continue;
  78310. }
  78311. v0.q = v1.q.add(v0.q);
  78312. v0.updatePosition(p);
  78313. var tStart = _this.references.length;
  78314. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  78315. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  78316. var tCount = _this.references.length - tStart;
  78317. if (tCount <= v0.triangleCount) {
  78318. if (tCount) {
  78319. for (var c = 0; c < tCount; c++) {
  78320. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  78321. }
  78322. }
  78323. }
  78324. else {
  78325. v0.triangleStart = tStart;
  78326. }
  78327. v0.triangleCount = tCount;
  78328. break;
  78329. }
  78330. }
  78331. };
  78332. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  78333. }, 0);
  78334. };
  78335. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  78336. if (triangleCount - deletedTriangles <= targetCount)
  78337. loop.breakLoop();
  78338. else {
  78339. iterationFunction(loop.index, function () {
  78340. loop.executeNext();
  78341. });
  78342. }
  78343. }, function () {
  78344. setTimeout(function () {
  78345. //reconstruct this part of the mesh
  78346. _this.reconstructMesh(submeshIndex);
  78347. successCallback();
  78348. }, 0);
  78349. });
  78350. };
  78351. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  78352. var _this = this;
  78353. this.vertices = [];
  78354. this.triangles = [];
  78355. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78356. var indices = this._mesh.getIndices();
  78357. var submesh = this._mesh.subMeshes[submeshIndex];
  78358. var findInVertices = function (positionToSearch) {
  78359. if (optimizeMesh) {
  78360. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  78361. if (_this.vertices[ii].position.equals(positionToSearch)) {
  78362. return _this.vertices[ii];
  78363. }
  78364. }
  78365. }
  78366. return null;
  78367. };
  78368. var vertexReferences = [];
  78369. var vertexInit = function (i) {
  78370. if (!positionData) {
  78371. return;
  78372. }
  78373. var offset = i + submesh.verticesStart;
  78374. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  78375. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  78376. vertex.originalOffsets.push(offset);
  78377. if (vertex.id === _this.vertices.length) {
  78378. _this.vertices.push(vertex);
  78379. }
  78380. vertexReferences.push(vertex.id);
  78381. };
  78382. //var totalVertices = mesh.getTotalVertices();
  78383. var totalVertices = submesh.verticesCount;
  78384. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  78385. var indicesInit = function (i) {
  78386. if (!indices) {
  78387. return;
  78388. }
  78389. var offset = (submesh.indexStart / 3) + i;
  78390. var pos = (offset * 3);
  78391. var i0 = indices[pos + 0];
  78392. var i1 = indices[pos + 1];
  78393. var i2 = indices[pos + 2];
  78394. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  78395. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  78396. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  78397. var triangle = new DecimationTriangle([v0, v1, v2]);
  78398. triangle.originalOffset = pos;
  78399. _this.triangles.push(triangle);
  78400. };
  78401. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  78402. _this.init(callback);
  78403. });
  78404. });
  78405. };
  78406. QuadraticErrorSimplification.prototype.init = function (callback) {
  78407. var _this = this;
  78408. var triangleInit1 = function (i) {
  78409. var t = _this.triangles[i];
  78410. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  78411. for (var j = 0; j < 3; j++) {
  78412. 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))));
  78413. }
  78414. };
  78415. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  78416. var triangleInit2 = function (i) {
  78417. var t = _this.triangles[i];
  78418. for (var j = 0; j < 3; ++j) {
  78419. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  78420. }
  78421. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78422. };
  78423. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  78424. callback();
  78425. });
  78426. });
  78427. };
  78428. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  78429. var newTriangles = [];
  78430. var i;
  78431. for (i = 0; i < this.vertices.length; ++i) {
  78432. this.vertices[i].triangleCount = 0;
  78433. }
  78434. var t;
  78435. var j;
  78436. for (i = 0; i < this.triangles.length; ++i) {
  78437. if (!this.triangles[i].deleted) {
  78438. t = this.triangles[i];
  78439. for (j = 0; j < 3; ++j) {
  78440. t.vertices[j].triangleCount = 1;
  78441. }
  78442. newTriangles.push(t);
  78443. }
  78444. }
  78445. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  78446. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  78447. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  78448. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  78449. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  78450. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78451. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  78452. var vertexCount = 0;
  78453. for (i = 0; i < this.vertices.length; ++i) {
  78454. var vertex = this.vertices[i];
  78455. vertex.id = vertexCount;
  78456. if (vertex.triangleCount) {
  78457. vertex.originalOffsets.forEach(function (originalOffset) {
  78458. if (!normalData) {
  78459. return;
  78460. }
  78461. newPositionData.push(vertex.position.x);
  78462. newPositionData.push(vertex.position.y);
  78463. newPositionData.push(vertex.position.z);
  78464. newNormalData.push(normalData[originalOffset * 3]);
  78465. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  78466. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  78467. if (uvs && uvs.length) {
  78468. newUVsData.push(uvs[(originalOffset * 2)]);
  78469. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  78470. }
  78471. else if (colorsData && colorsData.length) {
  78472. newColorsData.push(colorsData[(originalOffset * 4)]);
  78473. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  78474. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  78475. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  78476. }
  78477. ++vertexCount;
  78478. });
  78479. }
  78480. }
  78481. var startingIndex = this._reconstructedMesh.getTotalIndices();
  78482. var startingVertex = this._reconstructedMesh.getTotalVertices();
  78483. var submeshesArray = this._reconstructedMesh.subMeshes;
  78484. this._reconstructedMesh.subMeshes = [];
  78485. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  78486. var originalIndices = this._mesh.getIndices();
  78487. for (i = 0; i < newTriangles.length; ++i) {
  78488. t = newTriangles[i]; //now get the new referencing point for each vertex
  78489. [0, 1, 2].forEach(function (idx) {
  78490. var id = originalIndices[t.originalOffset + idx];
  78491. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  78492. if (offset < 0)
  78493. offset = 0;
  78494. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  78495. });
  78496. }
  78497. //overwriting the old vertex buffers and indices.
  78498. this._reconstructedMesh.setIndices(newIndicesArray);
  78499. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  78500. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  78501. if (newUVsData.length > 0)
  78502. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  78503. if (newColorsData.length > 0)
  78504. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  78505. //create submesh
  78506. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  78507. if (submeshIndex > 0) {
  78508. this._reconstructedMesh.subMeshes = [];
  78509. submeshesArray.forEach(function (submesh) {
  78510. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  78511. });
  78512. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  78513. }
  78514. };
  78515. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  78516. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  78517. this._reconstructedMesh.material = this._mesh.material;
  78518. this._reconstructedMesh.parent = this._mesh.parent;
  78519. this._reconstructedMesh.isVisible = false;
  78520. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  78521. };
  78522. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  78523. for (var i = 0; i < vertex1.triangleCount; ++i) {
  78524. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  78525. if (t.deleted)
  78526. continue;
  78527. var s = this.references[vertex1.triangleStart + i].vertexId;
  78528. var v1 = t.vertices[(s + 1) % 3];
  78529. var v2 = t.vertices[(s + 2) % 3];
  78530. if ((v1 === vertex2 || v2 === vertex2)) {
  78531. deletedArray[i] = true;
  78532. delTr.push(t);
  78533. continue;
  78534. }
  78535. var d1 = v1.position.subtract(point);
  78536. d1 = d1.normalize();
  78537. var d2 = v2.position.subtract(point);
  78538. d2 = d2.normalize();
  78539. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  78540. return true;
  78541. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  78542. deletedArray[i] = false;
  78543. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  78544. return true;
  78545. }
  78546. return false;
  78547. };
  78548. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  78549. var newDeleted = deletedTriangles;
  78550. for (var i = 0; i < vertex.triangleCount; ++i) {
  78551. var ref = this.references[vertex.triangleStart + i];
  78552. var t = this.triangles[ref.triangleId];
  78553. if (t.deleted)
  78554. continue;
  78555. if (deletedArray[i] && t.deletePending) {
  78556. t.deleted = true;
  78557. newDeleted++;
  78558. continue;
  78559. }
  78560. t.vertices[ref.vertexId] = origVertex;
  78561. t.isDirty = true;
  78562. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  78563. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  78564. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  78565. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78566. this.references.push(ref);
  78567. }
  78568. return newDeleted;
  78569. };
  78570. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  78571. for (var i = 0; i < this.vertices.length; ++i) {
  78572. var vCount = [];
  78573. var vId = [];
  78574. var v = this.vertices[i];
  78575. var j;
  78576. for (j = 0; j < v.triangleCount; ++j) {
  78577. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  78578. for (var ii = 0; ii < 3; ii++) {
  78579. var ofs = 0;
  78580. var vv = triangle.vertices[ii];
  78581. while (ofs < vCount.length) {
  78582. if (vId[ofs] === vv.id)
  78583. break;
  78584. ++ofs;
  78585. }
  78586. if (ofs === vCount.length) {
  78587. vCount.push(1);
  78588. vId.push(vv.id);
  78589. }
  78590. else {
  78591. vCount[ofs]++;
  78592. }
  78593. }
  78594. }
  78595. for (j = 0; j < vCount.length; ++j) {
  78596. if (vCount[j] === 1) {
  78597. this.vertices[vId[j]].isBorder = true;
  78598. }
  78599. else {
  78600. this.vertices[vId[j]].isBorder = false;
  78601. }
  78602. }
  78603. }
  78604. };
  78605. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  78606. if (identifyBorders === void 0) { identifyBorders = false; }
  78607. var i;
  78608. if (!identifyBorders) {
  78609. var newTrianglesVector = [];
  78610. for (i = 0; i < this.triangles.length; ++i) {
  78611. if (!this.triangles[i].deleted) {
  78612. newTrianglesVector.push(this.triangles[i]);
  78613. }
  78614. }
  78615. this.triangles = newTrianglesVector;
  78616. }
  78617. for (i = 0; i < this.vertices.length; ++i) {
  78618. this.vertices[i].triangleCount = 0;
  78619. this.vertices[i].triangleStart = 0;
  78620. }
  78621. var t;
  78622. var j;
  78623. var v;
  78624. for (i = 0; i < this.triangles.length; ++i) {
  78625. t = this.triangles[i];
  78626. for (j = 0; j < 3; ++j) {
  78627. v = t.vertices[j];
  78628. v.triangleCount++;
  78629. }
  78630. }
  78631. var tStart = 0;
  78632. for (i = 0; i < this.vertices.length; ++i) {
  78633. this.vertices[i].triangleStart = tStart;
  78634. tStart += this.vertices[i].triangleCount;
  78635. this.vertices[i].triangleCount = 0;
  78636. }
  78637. var newReferences = new Array(this.triangles.length * 3);
  78638. for (i = 0; i < this.triangles.length; ++i) {
  78639. t = this.triangles[i];
  78640. for (j = 0; j < 3; ++j) {
  78641. v = t.vertices[j];
  78642. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  78643. v.triangleCount++;
  78644. }
  78645. }
  78646. this.references = newReferences;
  78647. if (identifyBorders) {
  78648. this.identifyBorder();
  78649. }
  78650. };
  78651. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  78652. var x = point.x;
  78653. var y = point.y;
  78654. var z = point.z;
  78655. 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
  78656. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  78657. };
  78658. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  78659. var q = vertex1.q.add(vertex2.q);
  78660. var border = vertex1.isBorder && vertex2.isBorder;
  78661. var error = 0;
  78662. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  78663. if (qDet !== 0 && !border) {
  78664. if (!pointResult) {
  78665. pointResult = BABYLON.Vector3.Zero();
  78666. }
  78667. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  78668. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  78669. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  78670. error = this.vertexError(q, pointResult);
  78671. }
  78672. else {
  78673. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  78674. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  78675. var error1 = this.vertexError(q, vertex1.position);
  78676. var error2 = this.vertexError(q, vertex2.position);
  78677. var error3 = this.vertexError(q, p3);
  78678. error = Math.min(error1, error2, error3);
  78679. if (error === error1) {
  78680. if (pointResult) {
  78681. pointResult.copyFrom(vertex1.position);
  78682. }
  78683. }
  78684. else if (error === error2) {
  78685. if (pointResult) {
  78686. pointResult.copyFrom(vertex2.position);
  78687. }
  78688. }
  78689. else {
  78690. if (pointResult) {
  78691. pointResult.copyFrom(p3);
  78692. }
  78693. }
  78694. }
  78695. return error;
  78696. };
  78697. return QuadraticErrorSimplification;
  78698. }());
  78699. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  78700. })(BABYLON || (BABYLON = {}));
  78701. //# sourceMappingURL=babylon.meshSimplification.js.map
  78702. var BABYLON;
  78703. (function (BABYLON) {
  78704. var MeshLODLevel = /** @class */ (function () {
  78705. function MeshLODLevel(distance, mesh) {
  78706. this.distance = distance;
  78707. this.mesh = mesh;
  78708. }
  78709. return MeshLODLevel;
  78710. }());
  78711. BABYLON.MeshLODLevel = MeshLODLevel;
  78712. })(BABYLON || (BABYLON = {}));
  78713. //# sourceMappingURL=babylon.meshLODLevel.js.map
  78714. var BABYLON;
  78715. (function (BABYLON) {
  78716. /**
  78717. * Defines the root class used to create scene optimization to use with SceneOptimizer
  78718. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78719. */
  78720. var SceneOptimization = /** @class */ (function () {
  78721. /**
  78722. * Creates the SceneOptimization object
  78723. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78724. * @param desc defines the description associated with the optimization
  78725. */
  78726. function SceneOptimization(
  78727. /**
  78728. * Defines the priority of this optimization (0 by default which means first in the list)
  78729. */
  78730. priority) {
  78731. if (priority === void 0) { priority = 0; }
  78732. this.priority = priority;
  78733. }
  78734. /**
  78735. * Gets a string describing the action executed by the current optimization
  78736. * @returns description string
  78737. */
  78738. SceneOptimization.prototype.getDescription = function () {
  78739. return "";
  78740. };
  78741. /**
  78742. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78743. * @param scene defines the current scene where to apply this optimization
  78744. * @param optimizer defines the current optimizer
  78745. * @returns true if everything that can be done was applied
  78746. */
  78747. SceneOptimization.prototype.apply = function (scene, optimizer) {
  78748. return true;
  78749. };
  78750. ;
  78751. return SceneOptimization;
  78752. }());
  78753. BABYLON.SceneOptimization = SceneOptimization;
  78754. /**
  78755. * Defines an optimization used to reduce the size of render target textures
  78756. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78757. */
  78758. var TextureOptimization = /** @class */ (function (_super) {
  78759. __extends(TextureOptimization, _super);
  78760. /**
  78761. * Creates the TextureOptimization object
  78762. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78763. * @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
  78764. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78765. */
  78766. function TextureOptimization(
  78767. /**
  78768. * Defines the priority of this optimization (0 by default which means first in the list)
  78769. */
  78770. priority,
  78771. /**
  78772. * 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
  78773. */
  78774. maximumSize,
  78775. /**
  78776. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78777. */
  78778. step) {
  78779. if (priority === void 0) { priority = 0; }
  78780. if (maximumSize === void 0) { maximumSize = 1024; }
  78781. if (step === void 0) { step = 0.5; }
  78782. var _this = _super.call(this, priority) || this;
  78783. _this.priority = priority;
  78784. _this.maximumSize = maximumSize;
  78785. _this.step = step;
  78786. return _this;
  78787. }
  78788. /**
  78789. * Gets a string describing the action executed by the current optimization
  78790. * @returns description string
  78791. */
  78792. TextureOptimization.prototype.getDescription = function () {
  78793. return "Reducing render target texture size to " + this.maximumSize;
  78794. };
  78795. /**
  78796. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78797. * @param scene defines the current scene where to apply this optimization
  78798. * @param optimizer defines the current optimizer
  78799. * @returns true if everything that can be done was applied
  78800. */
  78801. TextureOptimization.prototype.apply = function (scene, optimizer) {
  78802. var allDone = true;
  78803. for (var index = 0; index < scene.textures.length; index++) {
  78804. var texture = scene.textures[index];
  78805. if (!texture.canRescale || texture.getContext) {
  78806. continue;
  78807. }
  78808. var currentSize = texture.getSize();
  78809. var maxDimension = Math.max(currentSize.width, currentSize.height);
  78810. if (maxDimension > this.maximumSize) {
  78811. texture.scale(this.step);
  78812. allDone = false;
  78813. }
  78814. }
  78815. return allDone;
  78816. };
  78817. return TextureOptimization;
  78818. }(SceneOptimization));
  78819. BABYLON.TextureOptimization = TextureOptimization;
  78820. /**
  78821. * Defines an optimization used to increase or decrease the rendering resolution
  78822. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78823. */
  78824. var HardwareScalingOptimization = /** @class */ (function (_super) {
  78825. __extends(HardwareScalingOptimization, _super);
  78826. /**
  78827. * Creates the HardwareScalingOptimization object
  78828. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78829. * @param maximumScale defines the maximum scale to use (2 by default)
  78830. * @param step defines the step to use between two passes (0.5 by default)
  78831. */
  78832. function HardwareScalingOptimization(
  78833. /**
  78834. * Defines the priority of this optimization (0 by default which means first in the list)
  78835. */
  78836. priority,
  78837. /**
  78838. * Defines the maximum scale to use (2 by default)
  78839. */
  78840. maximumScale,
  78841. /**
  78842. * Defines the step to use between two passes (0.5 by default)
  78843. */
  78844. step) {
  78845. if (priority === void 0) { priority = 0; }
  78846. if (maximumScale === void 0) { maximumScale = 2; }
  78847. if (step === void 0) { step = 0.25; }
  78848. var _this = _super.call(this, priority) || this;
  78849. _this.priority = priority;
  78850. _this.maximumScale = maximumScale;
  78851. _this.step = step;
  78852. _this._currentScale = -1;
  78853. _this._directionOffset = 1;
  78854. return _this;
  78855. }
  78856. /**
  78857. * Gets a string describing the action executed by the current optimization
  78858. * @return description string
  78859. */
  78860. HardwareScalingOptimization.prototype.getDescription = function () {
  78861. return "Setting hardware scaling level to " + this._currentScale;
  78862. };
  78863. /**
  78864. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78865. * @param scene defines the current scene where to apply this optimization
  78866. * @param optimizer defines the current optimizer
  78867. * @returns true if everything that can be done was applied
  78868. */
  78869. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  78870. if (this._currentScale === -1) {
  78871. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  78872. if (this._currentScale > this.maximumScale) {
  78873. this._directionOffset = -1;
  78874. }
  78875. }
  78876. this._currentScale += this._directionOffset * this.step;
  78877. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  78878. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  78879. };
  78880. ;
  78881. return HardwareScalingOptimization;
  78882. }(SceneOptimization));
  78883. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  78884. /**
  78885. * Defines an optimization used to remove shadows
  78886. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78887. */
  78888. var ShadowsOptimization = /** @class */ (function (_super) {
  78889. __extends(ShadowsOptimization, _super);
  78890. function ShadowsOptimization() {
  78891. return _super !== null && _super.apply(this, arguments) || this;
  78892. }
  78893. /**
  78894. * Gets a string describing the action executed by the current optimization
  78895. * @return description string
  78896. */
  78897. ShadowsOptimization.prototype.getDescription = function () {
  78898. return "Turning shadows on/off";
  78899. };
  78900. /**
  78901. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78902. * @param scene defines the current scene where to apply this optimization
  78903. * @param optimizer defines the current optimizer
  78904. * @returns true if everything that can be done was applied
  78905. */
  78906. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  78907. scene.shadowsEnabled = optimizer.isInImprovementMode;
  78908. return true;
  78909. };
  78910. ;
  78911. return ShadowsOptimization;
  78912. }(SceneOptimization));
  78913. BABYLON.ShadowsOptimization = ShadowsOptimization;
  78914. /**
  78915. * Defines an optimization used to turn post-processes off
  78916. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78917. */
  78918. var PostProcessesOptimization = /** @class */ (function (_super) {
  78919. __extends(PostProcessesOptimization, _super);
  78920. function PostProcessesOptimization() {
  78921. return _super !== null && _super.apply(this, arguments) || this;
  78922. }
  78923. /**
  78924. * Gets a string describing the action executed by the current optimization
  78925. * @return description string
  78926. */
  78927. PostProcessesOptimization.prototype.getDescription = function () {
  78928. return "Turning post-processes on/off";
  78929. };
  78930. /**
  78931. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78932. * @param scene defines the current scene where to apply this optimization
  78933. * @param optimizer defines the current optimizer
  78934. * @returns true if everything that can be done was applied
  78935. */
  78936. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  78937. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  78938. return true;
  78939. };
  78940. ;
  78941. return PostProcessesOptimization;
  78942. }(SceneOptimization));
  78943. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  78944. /**
  78945. * Defines an optimization used to turn lens flares off
  78946. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78947. */
  78948. var LensFlaresOptimization = /** @class */ (function (_super) {
  78949. __extends(LensFlaresOptimization, _super);
  78950. function LensFlaresOptimization() {
  78951. return _super !== null && _super.apply(this, arguments) || this;
  78952. }
  78953. /**
  78954. * Gets a string describing the action executed by the current optimization
  78955. * @return description string
  78956. */
  78957. LensFlaresOptimization.prototype.getDescription = function () {
  78958. return "Turning lens flares on/off";
  78959. };
  78960. /**
  78961. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78962. * @param scene defines the current scene where to apply this optimization
  78963. * @param optimizer defines the current optimizer
  78964. * @returns true if everything that can be done was applied
  78965. */
  78966. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  78967. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  78968. return true;
  78969. };
  78970. ;
  78971. return LensFlaresOptimization;
  78972. }(SceneOptimization));
  78973. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  78974. /**
  78975. * Defines an optimization based on user defined callback.
  78976. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78977. */
  78978. var CustomOptimization = /** @class */ (function (_super) {
  78979. __extends(CustomOptimization, _super);
  78980. function CustomOptimization() {
  78981. return _super !== null && _super.apply(this, arguments) || this;
  78982. }
  78983. /**
  78984. * Gets a string describing the action executed by the current optimization
  78985. * @returns description string
  78986. */
  78987. CustomOptimization.prototype.getDescription = function () {
  78988. if (this.onGetDescription) {
  78989. return this.onGetDescription();
  78990. }
  78991. return "Running user defined callback";
  78992. };
  78993. /**
  78994. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78995. * @param scene defines the current scene where to apply this optimization
  78996. * @param optimizer defines the current optimizer
  78997. * @returns true if everything that can be done was applied
  78998. */
  78999. CustomOptimization.prototype.apply = function (scene, optimizer) {
  79000. if (this.onApply) {
  79001. return this.onApply(scene, optimizer);
  79002. }
  79003. return true;
  79004. };
  79005. ;
  79006. return CustomOptimization;
  79007. }(SceneOptimization));
  79008. BABYLON.CustomOptimization = CustomOptimization;
  79009. /**
  79010. * Defines an optimization used to turn particles off
  79011. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79012. */
  79013. var ParticlesOptimization = /** @class */ (function (_super) {
  79014. __extends(ParticlesOptimization, _super);
  79015. function ParticlesOptimization() {
  79016. return _super !== null && _super.apply(this, arguments) || this;
  79017. }
  79018. /**
  79019. * Gets a string describing the action executed by the current optimization
  79020. * @return description string
  79021. */
  79022. ParticlesOptimization.prototype.getDescription = function () {
  79023. return "Turning particles on/off";
  79024. };
  79025. /**
  79026. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79027. * @param scene defines the current scene where to apply this optimization
  79028. * @param optimizer defines the current optimizer
  79029. * @returns true if everything that can be done was applied
  79030. */
  79031. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  79032. scene.particlesEnabled = optimizer.isInImprovementMode;
  79033. return true;
  79034. };
  79035. ;
  79036. return ParticlesOptimization;
  79037. }(SceneOptimization));
  79038. BABYLON.ParticlesOptimization = ParticlesOptimization;
  79039. /**
  79040. * Defines an optimization used to turn render targets off
  79041. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79042. */
  79043. var RenderTargetsOptimization = /** @class */ (function (_super) {
  79044. __extends(RenderTargetsOptimization, _super);
  79045. function RenderTargetsOptimization() {
  79046. return _super !== null && _super.apply(this, arguments) || this;
  79047. }
  79048. /**
  79049. * Gets a string describing the action executed by the current optimization
  79050. * @return description string
  79051. */
  79052. RenderTargetsOptimization.prototype.getDescription = function () {
  79053. return "Turning render targets off";
  79054. };
  79055. /**
  79056. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79057. * @param scene defines the current scene where to apply this optimization
  79058. * @param optimizer defines the current optimizer
  79059. * @returns true if everything that can be done was applied
  79060. */
  79061. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  79062. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  79063. return true;
  79064. };
  79065. ;
  79066. return RenderTargetsOptimization;
  79067. }(SceneOptimization));
  79068. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  79069. /**
  79070. * Defines an optimization used to merge meshes with compatible materials
  79071. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79072. */
  79073. var MergeMeshesOptimization = /** @class */ (function (_super) {
  79074. __extends(MergeMeshesOptimization, _super);
  79075. function MergeMeshesOptimization() {
  79076. var _this = _super !== null && _super.apply(this, arguments) || this;
  79077. _this._canBeMerged = function (abstractMesh) {
  79078. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  79079. return false;
  79080. }
  79081. var mesh = abstractMesh;
  79082. if (!mesh.isVisible || !mesh.isEnabled()) {
  79083. return false;
  79084. }
  79085. if (mesh.instances.length > 0) {
  79086. return false;
  79087. }
  79088. if (mesh.skeleton || mesh.hasLODLevels) {
  79089. return false;
  79090. }
  79091. if (mesh.parent) {
  79092. return false;
  79093. }
  79094. return true;
  79095. };
  79096. return _this;
  79097. }
  79098. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  79099. /**
  79100. * Gets or sets a boolean which defines if optimization octree has to be updated
  79101. */
  79102. get: function () {
  79103. return MergeMeshesOptimization._UpdateSelectionTree;
  79104. },
  79105. /**
  79106. * Gets or sets a boolean which defines if optimization octree has to be updated
  79107. */
  79108. set: function (value) {
  79109. MergeMeshesOptimization._UpdateSelectionTree = value;
  79110. },
  79111. enumerable: true,
  79112. configurable: true
  79113. });
  79114. /**
  79115. * Gets a string describing the action executed by the current optimization
  79116. * @return description string
  79117. */
  79118. MergeMeshesOptimization.prototype.getDescription = function () {
  79119. return "Merging similar meshes together";
  79120. };
  79121. /**
  79122. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79123. * @param scene defines the current scene where to apply this optimization
  79124. * @param optimizer defines the current optimizer
  79125. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  79126. * @returns true if everything that can be done was applied
  79127. */
  79128. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  79129. var globalPool = scene.meshes.slice(0);
  79130. var globalLength = globalPool.length;
  79131. for (var index = 0; index < globalLength; index++) {
  79132. var currentPool = new Array();
  79133. var current = globalPool[index];
  79134. // Checks
  79135. if (!this._canBeMerged(current)) {
  79136. continue;
  79137. }
  79138. currentPool.push(current);
  79139. // Find compatible meshes
  79140. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  79141. var otherMesh = globalPool[subIndex];
  79142. if (!this._canBeMerged(otherMesh)) {
  79143. continue;
  79144. }
  79145. if (otherMesh.material !== current.material) {
  79146. continue;
  79147. }
  79148. if (otherMesh.checkCollisions !== current.checkCollisions) {
  79149. continue;
  79150. }
  79151. currentPool.push(otherMesh);
  79152. globalLength--;
  79153. globalPool.splice(subIndex, 1);
  79154. subIndex--;
  79155. }
  79156. if (currentPool.length < 2) {
  79157. continue;
  79158. }
  79159. // Merge meshes
  79160. BABYLON.Mesh.MergeMeshes(currentPool);
  79161. }
  79162. if (updateSelectionTree != undefined) {
  79163. if (updateSelectionTree) {
  79164. scene.createOrUpdateSelectionOctree();
  79165. }
  79166. }
  79167. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  79168. scene.createOrUpdateSelectionOctree();
  79169. }
  79170. return true;
  79171. };
  79172. ;
  79173. MergeMeshesOptimization._UpdateSelectionTree = false;
  79174. return MergeMeshesOptimization;
  79175. }(SceneOptimization));
  79176. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  79177. /**
  79178. * Defines a list of options used by SceneOptimizer
  79179. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79180. */
  79181. var SceneOptimizerOptions = /** @class */ (function () {
  79182. /**
  79183. * Creates a new list of options used by SceneOptimizer
  79184. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  79185. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  79186. */
  79187. function SceneOptimizerOptions(
  79188. /**
  79189. * Defines the target frame rate to reach (60 by default)
  79190. */
  79191. targetFrameRate,
  79192. /**
  79193. * Defines the interval between two checkes (2000ms by default)
  79194. */
  79195. trackerDuration) {
  79196. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  79197. if (trackerDuration === void 0) { trackerDuration = 2000; }
  79198. this.targetFrameRate = targetFrameRate;
  79199. this.trackerDuration = trackerDuration;
  79200. /**
  79201. * Gets the list of optimizations to apply
  79202. */
  79203. this.optimizations = new Array();
  79204. }
  79205. /**
  79206. * Add a new optimization
  79207. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  79208. * @returns the current SceneOptimizerOptions
  79209. */
  79210. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  79211. this.optimizations.push(optimization);
  79212. return this;
  79213. };
  79214. /**
  79215. * Add a new custom optimization
  79216. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  79217. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  79218. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79219. * @returns the current SceneOptimizerOptions
  79220. */
  79221. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  79222. if (priority === void 0) { priority = 0; }
  79223. var optimization = new CustomOptimization(priority);
  79224. optimization.onApply = onApply;
  79225. optimization.onGetDescription = onGetDescription;
  79226. this.optimizations.push(optimization);
  79227. return this;
  79228. };
  79229. /**
  79230. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  79231. * @param targetFrameRate defines the target frame rate (60 by default)
  79232. * @returns a SceneOptimizerOptions object
  79233. */
  79234. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  79235. var result = new SceneOptimizerOptions(targetFrameRate);
  79236. var priority = 0;
  79237. result.addOptimization(new MergeMeshesOptimization(priority));
  79238. result.addOptimization(new ShadowsOptimization(priority));
  79239. result.addOptimization(new LensFlaresOptimization(priority));
  79240. // Next priority
  79241. priority++;
  79242. result.addOptimization(new PostProcessesOptimization(priority));
  79243. result.addOptimization(new ParticlesOptimization(priority));
  79244. // Next priority
  79245. priority++;
  79246. result.addOptimization(new TextureOptimization(priority, 1024));
  79247. return result;
  79248. };
  79249. /**
  79250. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  79251. * @param targetFrameRate defines the target frame rate (60 by default)
  79252. * @returns a SceneOptimizerOptions object
  79253. */
  79254. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  79255. var result = new SceneOptimizerOptions(targetFrameRate);
  79256. var priority = 0;
  79257. result.addOptimization(new MergeMeshesOptimization(priority));
  79258. result.addOptimization(new ShadowsOptimization(priority));
  79259. result.addOptimization(new LensFlaresOptimization(priority));
  79260. // Next priority
  79261. priority++;
  79262. result.addOptimization(new PostProcessesOptimization(priority));
  79263. result.addOptimization(new ParticlesOptimization(priority));
  79264. // Next priority
  79265. priority++;
  79266. result.addOptimization(new TextureOptimization(priority, 512));
  79267. // Next priority
  79268. priority++;
  79269. result.addOptimization(new RenderTargetsOptimization(priority));
  79270. // Next priority
  79271. priority++;
  79272. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  79273. return result;
  79274. };
  79275. /**
  79276. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  79277. * @param targetFrameRate defines the target frame rate (60 by default)
  79278. * @returns a SceneOptimizerOptions object
  79279. */
  79280. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  79281. var result = new SceneOptimizerOptions(targetFrameRate);
  79282. var priority = 0;
  79283. result.addOptimization(new MergeMeshesOptimization(priority));
  79284. result.addOptimization(new ShadowsOptimization(priority));
  79285. result.addOptimization(new LensFlaresOptimization(priority));
  79286. // Next priority
  79287. priority++;
  79288. result.addOptimization(new PostProcessesOptimization(priority));
  79289. result.addOptimization(new ParticlesOptimization(priority));
  79290. // Next priority
  79291. priority++;
  79292. result.addOptimization(new TextureOptimization(priority, 256));
  79293. // Next priority
  79294. priority++;
  79295. result.addOptimization(new RenderTargetsOptimization(priority));
  79296. // Next priority
  79297. priority++;
  79298. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  79299. return result;
  79300. };
  79301. return SceneOptimizerOptions;
  79302. }());
  79303. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  79304. /**
  79305. * Class used to run optimizations in order to reach a target frame rate
  79306. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79307. */
  79308. var SceneOptimizer = /** @class */ (function () {
  79309. /**
  79310. * Creates a new SceneOptimizer
  79311. * @param scene defines the scene to work on
  79312. * @param options defines the options to use with the SceneOptimizer
  79313. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  79314. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  79315. */
  79316. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  79317. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  79318. if (improvementMode === void 0) { improvementMode = false; }
  79319. var _this = this;
  79320. this._isRunning = false;
  79321. this._currentPriorityLevel = 0;
  79322. this._targetFrameRate = 60;
  79323. this._trackerDuration = 2000;
  79324. this._currentFrameRate = 0;
  79325. this._improvementMode = false;
  79326. /**
  79327. * Defines an observable called when the optimizer reaches the target frame rate
  79328. */
  79329. this.onSuccessObservable = new BABYLON.Observable();
  79330. /**
  79331. * Defines an observable called when the optimizer enables an optimization
  79332. */
  79333. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  79334. /**
  79335. * Defines an observable called when the optimizer is not able to reach the target frame rate
  79336. */
  79337. this.onFailureObservable = new BABYLON.Observable();
  79338. if (!options) {
  79339. this._options = new SceneOptimizerOptions();
  79340. }
  79341. else {
  79342. this._options = options;
  79343. }
  79344. if (this._options.targetFrameRate) {
  79345. this._targetFrameRate = this._options.targetFrameRate;
  79346. }
  79347. if (this._options.trackerDuration) {
  79348. this._trackerDuration = this._options.trackerDuration;
  79349. }
  79350. if (autoGeneratePriorities) {
  79351. var priority = 0;
  79352. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  79353. var optim = _a[_i];
  79354. optim.priority = priority++;
  79355. }
  79356. }
  79357. this._improvementMode = improvementMode;
  79358. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79359. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  79360. _this._sceneDisposeObserver = null;
  79361. _this.dispose();
  79362. });
  79363. }
  79364. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  79365. /**
  79366. * Gets a boolean indicating if the optimizer is in improvement mode
  79367. */
  79368. get: function () {
  79369. return this._improvementMode;
  79370. },
  79371. enumerable: true,
  79372. configurable: true
  79373. });
  79374. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  79375. /**
  79376. * Gets the current priority level (0 at start)
  79377. */
  79378. get: function () {
  79379. return this._currentPriorityLevel;
  79380. },
  79381. enumerable: true,
  79382. configurable: true
  79383. });
  79384. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  79385. /**
  79386. * Gets the current frame rate checked by the SceneOptimizer
  79387. */
  79388. get: function () {
  79389. return this._currentFrameRate;
  79390. },
  79391. enumerable: true,
  79392. configurable: true
  79393. });
  79394. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  79395. /**
  79396. * Gets or sets the current target frame rate (60 by default)
  79397. */
  79398. get: function () {
  79399. return this._targetFrameRate;
  79400. },
  79401. /**
  79402. * Gets or sets the current target frame rate (60 by default)
  79403. */
  79404. set: function (value) {
  79405. this._targetFrameRate = value;
  79406. },
  79407. enumerable: true,
  79408. configurable: true
  79409. });
  79410. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  79411. /**
  79412. * Gets or sets the current interval between two checks (every 2000ms by default)
  79413. */
  79414. get: function () {
  79415. return this._trackerDuration;
  79416. },
  79417. /**
  79418. * Gets or sets the current interval between two checks (every 2000ms by default)
  79419. */
  79420. set: function (value) {
  79421. this._trackerDuration = value;
  79422. },
  79423. enumerable: true,
  79424. configurable: true
  79425. });
  79426. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  79427. /**
  79428. * Gets the list of active optimizations
  79429. */
  79430. get: function () {
  79431. return this._options.optimizations;
  79432. },
  79433. enumerable: true,
  79434. configurable: true
  79435. });
  79436. /**
  79437. * Stops the current optimizer
  79438. */
  79439. SceneOptimizer.prototype.stop = function () {
  79440. this._isRunning = false;
  79441. };
  79442. /**
  79443. * Reset the optimizer to initial step (current priority level = 0)
  79444. */
  79445. SceneOptimizer.prototype.reset = function () {
  79446. this._currentPriorityLevel = 0;
  79447. };
  79448. /**
  79449. * Start the optimizer. By default it will try to reach a specific framerate
  79450. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  79451. */
  79452. SceneOptimizer.prototype.start = function () {
  79453. var _this = this;
  79454. if (this._isRunning) {
  79455. return;
  79456. }
  79457. this._isRunning = true;
  79458. // Let's wait for the scene to be ready before running our check
  79459. this._scene.executeWhenReady(function () {
  79460. setTimeout(function () {
  79461. _this._checkCurrentState();
  79462. }, _this._trackerDuration);
  79463. });
  79464. };
  79465. SceneOptimizer.prototype._checkCurrentState = function () {
  79466. var _this = this;
  79467. if (!this._isRunning) {
  79468. return;
  79469. }
  79470. var scene = this._scene;
  79471. var options = this._options;
  79472. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  79473. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  79474. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  79475. this._isRunning = false;
  79476. this.onSuccessObservable.notifyObservers(this);
  79477. return;
  79478. }
  79479. // Apply current level of optimizations
  79480. var allDone = true;
  79481. var noOptimizationApplied = true;
  79482. for (var index = 0; index < options.optimizations.length; index++) {
  79483. var optimization = options.optimizations[index];
  79484. if (optimization.priority === this._currentPriorityLevel) {
  79485. noOptimizationApplied = false;
  79486. allDone = allDone && optimization.apply(scene, this);
  79487. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  79488. }
  79489. }
  79490. // If no optimization was applied, this is a failure :(
  79491. if (noOptimizationApplied) {
  79492. this._isRunning = false;
  79493. this.onFailureObservable.notifyObservers(this);
  79494. return;
  79495. }
  79496. // If all optimizations were done, move to next level
  79497. if (allDone) {
  79498. this._currentPriorityLevel++;
  79499. }
  79500. // Let's the system running for a specific amount of time before checking FPS
  79501. scene.executeWhenReady(function () {
  79502. setTimeout(function () {
  79503. _this._checkCurrentState();
  79504. }, _this._trackerDuration);
  79505. });
  79506. };
  79507. /**
  79508. * Release all resources
  79509. */
  79510. SceneOptimizer.prototype.dispose = function () {
  79511. this.stop();
  79512. this.onSuccessObservable.clear();
  79513. this.onFailureObservable.clear();
  79514. this.onNewOptimizationAppliedObservable.clear();
  79515. if (this._sceneDisposeObserver) {
  79516. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  79517. }
  79518. };
  79519. /**
  79520. * Helper function to create a SceneOptimizer with one single line of code
  79521. * @param scene defines the scene to work on
  79522. * @param options defines the options to use with the SceneOptimizer
  79523. * @param onSuccess defines a callback to call on success
  79524. * @param onFailure defines a callback to call on failure
  79525. * @returns the new SceneOptimizer object
  79526. */
  79527. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  79528. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  79529. if (onSuccess) {
  79530. optimizer.onSuccessObservable.add(function () {
  79531. onSuccess();
  79532. });
  79533. }
  79534. if (onFailure) {
  79535. optimizer.onFailureObservable.add(function () {
  79536. onFailure();
  79537. });
  79538. }
  79539. optimizer.start();
  79540. return optimizer;
  79541. };
  79542. return SceneOptimizer;
  79543. }());
  79544. BABYLON.SceneOptimizer = SceneOptimizer;
  79545. })(BABYLON || (BABYLON = {}));
  79546. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  79547. var BABYLON;
  79548. (function (BABYLON) {
  79549. var OutlineRenderer = /** @class */ (function () {
  79550. function OutlineRenderer(scene) {
  79551. this.zOffset = 1;
  79552. this._scene = scene;
  79553. }
  79554. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  79555. var _this = this;
  79556. if (useOverlay === void 0) { useOverlay = false; }
  79557. var scene = this._scene;
  79558. var engine = this._scene.getEngine();
  79559. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79560. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  79561. return;
  79562. }
  79563. var mesh = subMesh.getRenderingMesh();
  79564. var material = subMesh.getMaterial();
  79565. if (!material || !scene.activeCamera) {
  79566. return;
  79567. }
  79568. engine.enableEffect(this._effect);
  79569. // Logarithmic depth
  79570. if (material.useLogarithmicDepth) {
  79571. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  79572. }
  79573. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  79574. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  79575. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79576. // Bones
  79577. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79578. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79579. }
  79580. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  79581. // Alpha test
  79582. if (material && material.needAlphaTesting()) {
  79583. var alphaTexture = material.getAlphaTestTexture();
  79584. if (alphaTexture) {
  79585. this._effect.setTexture("diffuseSampler", alphaTexture);
  79586. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79587. }
  79588. }
  79589. engine.setZOffset(-this.zOffset);
  79590. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  79591. engine.setZOffset(0);
  79592. };
  79593. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  79594. var defines = [];
  79595. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79596. var mesh = subMesh.getMesh();
  79597. var material = subMesh.getMaterial();
  79598. if (material) {
  79599. // Alpha test
  79600. if (material.needAlphaTesting()) {
  79601. defines.push("#define ALPHATEST");
  79602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79603. attribs.push(BABYLON.VertexBuffer.UVKind);
  79604. defines.push("#define UV1");
  79605. }
  79606. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79607. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79608. defines.push("#define UV2");
  79609. }
  79610. }
  79611. //Logarithmic depth
  79612. if (material.useLogarithmicDepth) {
  79613. defines.push("#define LOGARITHMICDEPTH");
  79614. }
  79615. }
  79616. // Bones
  79617. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79620. if (mesh.numBoneInfluencers > 4) {
  79621. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79622. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79623. }
  79624. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79625. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79626. }
  79627. else {
  79628. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79629. }
  79630. // Instances
  79631. if (useInstances) {
  79632. defines.push("#define INSTANCES");
  79633. attribs.push("world0");
  79634. attribs.push("world1");
  79635. attribs.push("world2");
  79636. attribs.push("world3");
  79637. }
  79638. // Get correct effect
  79639. var join = defines.join("\n");
  79640. if (this._cachedDefines !== join) {
  79641. this._cachedDefines = join;
  79642. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  79643. }
  79644. return this._effect.isReady();
  79645. };
  79646. return OutlineRenderer;
  79647. }());
  79648. BABYLON.OutlineRenderer = OutlineRenderer;
  79649. })(BABYLON || (BABYLON = {}));
  79650. //# sourceMappingURL=babylon.outlineRenderer.js.map
  79651. var BABYLON;
  79652. (function (BABYLON) {
  79653. var FaceAdjacencies = /** @class */ (function () {
  79654. function FaceAdjacencies() {
  79655. this.edges = new Array();
  79656. this.edgesConnectedCount = 0;
  79657. }
  79658. return FaceAdjacencies;
  79659. }());
  79660. var EdgesRenderer = /** @class */ (function () {
  79661. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  79662. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  79663. if (epsilon === void 0) { epsilon = 0.95; }
  79664. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  79665. this.edgesWidthScalerForOrthographic = 1000.0;
  79666. this.edgesWidthScalerForPerspective = 50.0;
  79667. this._linesPositions = new Array();
  79668. this._linesNormals = new Array();
  79669. this._linesIndices = new Array();
  79670. this._buffers = {};
  79671. this._checkVerticesInsteadOfIndices = false;
  79672. this._source = source;
  79673. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  79674. this._epsilon = epsilon;
  79675. this._prepareRessources();
  79676. this._generateEdgesLines();
  79677. }
  79678. EdgesRenderer.prototype._prepareRessources = function () {
  79679. if (this._lineShader) {
  79680. return;
  79681. }
  79682. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  79683. attributes: ["position", "normal"],
  79684. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  79685. });
  79686. this._lineShader.disableDepthWrite = true;
  79687. this._lineShader.backFaceCulling = false;
  79688. };
  79689. EdgesRenderer.prototype._rebuild = function () {
  79690. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79691. if (buffer) {
  79692. buffer._rebuild();
  79693. }
  79694. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79695. if (buffer) {
  79696. buffer._rebuild();
  79697. }
  79698. var scene = this._source.getScene();
  79699. var engine = scene.getEngine();
  79700. this._ib = engine.createIndexBuffer(this._linesIndices);
  79701. };
  79702. EdgesRenderer.prototype.dispose = function () {
  79703. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79704. if (buffer) {
  79705. buffer.dispose();
  79706. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  79707. }
  79708. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79709. if (buffer) {
  79710. buffer.dispose();
  79711. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  79712. }
  79713. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  79714. this._lineShader.dispose();
  79715. };
  79716. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  79717. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  79718. return 0;
  79719. }
  79720. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  79721. return 1;
  79722. }
  79723. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  79724. return 2;
  79725. }
  79726. return -1;
  79727. };
  79728. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  79729. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  79730. return 0;
  79731. }
  79732. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  79733. return 1;
  79734. }
  79735. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  79736. return 2;
  79737. }
  79738. return -1;
  79739. };
  79740. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  79741. var needToCreateLine;
  79742. if (edge === undefined) {
  79743. needToCreateLine = true;
  79744. }
  79745. else {
  79746. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  79747. needToCreateLine = dotProduct < this._epsilon;
  79748. }
  79749. if (needToCreateLine) {
  79750. var offset = this._linesPositions.length / 3;
  79751. var normal = p0.subtract(p1);
  79752. normal.normalize();
  79753. // Positions
  79754. this._linesPositions.push(p0.x);
  79755. this._linesPositions.push(p0.y);
  79756. this._linesPositions.push(p0.z);
  79757. this._linesPositions.push(p0.x);
  79758. this._linesPositions.push(p0.y);
  79759. this._linesPositions.push(p0.z);
  79760. this._linesPositions.push(p1.x);
  79761. this._linesPositions.push(p1.y);
  79762. this._linesPositions.push(p1.z);
  79763. this._linesPositions.push(p1.x);
  79764. this._linesPositions.push(p1.y);
  79765. this._linesPositions.push(p1.z);
  79766. // Normals
  79767. this._linesNormals.push(p1.x);
  79768. this._linesNormals.push(p1.y);
  79769. this._linesNormals.push(p1.z);
  79770. this._linesNormals.push(-1);
  79771. this._linesNormals.push(p1.x);
  79772. this._linesNormals.push(p1.y);
  79773. this._linesNormals.push(p1.z);
  79774. this._linesNormals.push(1);
  79775. this._linesNormals.push(p0.x);
  79776. this._linesNormals.push(p0.y);
  79777. this._linesNormals.push(p0.z);
  79778. this._linesNormals.push(-1);
  79779. this._linesNormals.push(p0.x);
  79780. this._linesNormals.push(p0.y);
  79781. this._linesNormals.push(p0.z);
  79782. this._linesNormals.push(1);
  79783. // Indices
  79784. this._linesIndices.push(offset);
  79785. this._linesIndices.push(offset + 1);
  79786. this._linesIndices.push(offset + 2);
  79787. this._linesIndices.push(offset);
  79788. this._linesIndices.push(offset + 2);
  79789. this._linesIndices.push(offset + 3);
  79790. }
  79791. };
  79792. EdgesRenderer.prototype._generateEdgesLines = function () {
  79793. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  79794. var indices = this._source.getIndices();
  79795. if (!indices || !positions) {
  79796. return;
  79797. }
  79798. // First let's find adjacencies
  79799. var adjacencies = new Array();
  79800. var faceNormals = new Array();
  79801. var index;
  79802. var faceAdjacencies;
  79803. // Prepare faces
  79804. for (index = 0; index < indices.length; index += 3) {
  79805. faceAdjacencies = new FaceAdjacencies();
  79806. var p0Index = indices[index];
  79807. var p1Index = indices[index + 1];
  79808. var p2Index = indices[index + 2];
  79809. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  79810. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  79811. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  79812. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  79813. faceNormal.normalize();
  79814. faceNormals.push(faceNormal);
  79815. adjacencies.push(faceAdjacencies);
  79816. }
  79817. // Scan
  79818. for (index = 0; index < adjacencies.length; index++) {
  79819. faceAdjacencies = adjacencies[index];
  79820. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  79821. var otherFaceAdjacencies = adjacencies[otherIndex];
  79822. if (faceAdjacencies.edgesConnectedCount === 3) {
  79823. break;
  79824. }
  79825. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  79826. continue;
  79827. }
  79828. var otherP0 = indices[otherIndex * 3];
  79829. var otherP1 = indices[otherIndex * 3 + 1];
  79830. var otherP2 = indices[otherIndex * 3 + 2];
  79831. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  79832. var otherEdgeIndex = 0;
  79833. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  79834. continue;
  79835. }
  79836. switch (edgeIndex) {
  79837. case 0:
  79838. if (this._checkVerticesInsteadOfIndices) {
  79839. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79840. }
  79841. else {
  79842. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  79843. }
  79844. break;
  79845. case 1:
  79846. if (this._checkVerticesInsteadOfIndices) {
  79847. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79848. }
  79849. else {
  79850. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  79851. }
  79852. break;
  79853. case 2:
  79854. if (this._checkVerticesInsteadOfIndices) {
  79855. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79856. }
  79857. else {
  79858. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  79859. }
  79860. break;
  79861. }
  79862. if (otherEdgeIndex === -1) {
  79863. continue;
  79864. }
  79865. faceAdjacencies.edges[edgeIndex] = otherIndex;
  79866. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  79867. faceAdjacencies.edgesConnectedCount++;
  79868. otherFaceAdjacencies.edgesConnectedCount++;
  79869. if (faceAdjacencies.edgesConnectedCount === 3) {
  79870. break;
  79871. }
  79872. }
  79873. }
  79874. }
  79875. // Create lines
  79876. for (index = 0; index < adjacencies.length; index++) {
  79877. // 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
  79878. var current = adjacencies[index];
  79879. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  79880. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  79881. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  79882. }
  79883. // Merge into a single mesh
  79884. var engine = this._source.getScene().getEngine();
  79885. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  79886. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  79887. this._ib = engine.createIndexBuffer(this._linesIndices);
  79888. this._indicesCount = this._linesIndices.length;
  79889. };
  79890. EdgesRenderer.prototype.render = function () {
  79891. var scene = this._source.getScene();
  79892. if (!this._lineShader.isReady() || !scene.activeCamera) {
  79893. return;
  79894. }
  79895. var engine = scene.getEngine();
  79896. this._lineShader._preBind();
  79897. // VBOs
  79898. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  79899. scene.resetCachedMaterial();
  79900. this._lineShader.setColor4("color", this._source.edgesColor);
  79901. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  79902. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  79903. }
  79904. else {
  79905. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  79906. }
  79907. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  79908. this._lineShader.bind(this._source.getWorldMatrix());
  79909. // Draw order
  79910. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  79911. this._lineShader.unbind();
  79912. engine.setDepthWrite(true);
  79913. };
  79914. return EdgesRenderer;
  79915. }());
  79916. BABYLON.EdgesRenderer = EdgesRenderer;
  79917. })(BABYLON || (BABYLON = {}));
  79918. //# sourceMappingURL=babylon.edgesRenderer.js.map
  79919. var BABYLON;
  79920. (function (BABYLON) {
  79921. /**
  79922. * Special Glow Blur post process only blurring the alpha channel
  79923. * It enforces keeping the most luminous color in the color channel.
  79924. */
  79925. var GlowBlurPostProcess = /** @class */ (function (_super) {
  79926. __extends(GlowBlurPostProcess, _super);
  79927. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  79928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79929. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  79930. _this.direction = direction;
  79931. _this.kernel = kernel;
  79932. _this.onApplyObservable.add(function (effect) {
  79933. effect.setFloat2("screenSize", _this.width, _this.height);
  79934. effect.setVector2("direction", _this.direction);
  79935. effect.setFloat("blurWidth", _this.kernel);
  79936. });
  79937. return _this;
  79938. }
  79939. return GlowBlurPostProcess;
  79940. }(BABYLON.PostProcess));
  79941. /**
  79942. * The highlight layer Helps adding a glow effect around a mesh.
  79943. *
  79944. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  79945. * glowy meshes to your scene.
  79946. *
  79947. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  79948. */
  79949. var HighlightLayer = /** @class */ (function () {
  79950. /**
  79951. * Instantiates a new highlight Layer and references it to the scene..
  79952. * @param name The name of the layer
  79953. * @param scene The scene to use the layer in
  79954. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  79955. */
  79956. function HighlightLayer(name, scene, options) {
  79957. this.name = name;
  79958. this._vertexBuffers = {};
  79959. this._mainTextureDesiredSize = { width: 0, height: 0 };
  79960. this._meshes = {};
  79961. this._maxSize = 0;
  79962. this._shouldRender = false;
  79963. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  79964. this._excludedMeshes = {};
  79965. /**
  79966. * Specifies whether or not the inner glow is ACTIVE in the layer.
  79967. */
  79968. this.innerGlow = true;
  79969. /**
  79970. * Specifies whether or not the outer glow is ACTIVE in the layer.
  79971. */
  79972. this.outerGlow = true;
  79973. /**
  79974. * Specifies wether the highlight layer is enabled or not.
  79975. */
  79976. this.isEnabled = true;
  79977. /**
  79978. * An event triggered when the highlight layer has been disposed.
  79979. * @type {BABYLON.Observable}
  79980. */
  79981. this.onDisposeObservable = new BABYLON.Observable();
  79982. /**
  79983. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  79984. * @type {BABYLON.Observable}
  79985. */
  79986. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  79987. /**
  79988. * An event triggered when the highlight layer is being blurred.
  79989. * @type {BABYLON.Observable}
  79990. */
  79991. this.onBeforeBlurObservable = new BABYLON.Observable();
  79992. /**
  79993. * An event triggered when the highlight layer has been blurred.
  79994. * @type {BABYLON.Observable}
  79995. */
  79996. this.onAfterBlurObservable = new BABYLON.Observable();
  79997. /**
  79998. * An event triggered when the glowing blurred texture is being merged in the scene.
  79999. * @type {BABYLON.Observable}
  80000. */
  80001. this.onBeforeComposeObservable = new BABYLON.Observable();
  80002. /**
  80003. * An event triggered when the glowing blurred texture has been merged in the scene.
  80004. * @type {BABYLON.Observable}
  80005. */
  80006. this.onAfterComposeObservable = new BABYLON.Observable();
  80007. /**
  80008. * An event triggered when the highlight layer changes its size.
  80009. * @type {BABYLON.Observable}
  80010. */
  80011. this.onSizeChangedObservable = new BABYLON.Observable();
  80012. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80013. var engine = scene.getEngine();
  80014. this._engine = engine;
  80015. this._maxSize = this._engine.getCaps().maxTextureSize;
  80016. this._scene.highlightLayers.push(this);
  80017. // Warn on stencil.
  80018. if (!this._engine.isStencilEnable) {
  80019. 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 }");
  80020. }
  80021. // Adapt options
  80022. this._options = options || {
  80023. mainTextureRatio: 0.5,
  80024. blurTextureSizeRatio: 0.5,
  80025. blurHorizontalSize: 1.0,
  80026. blurVerticalSize: 1.0,
  80027. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  80028. camera: null
  80029. };
  80030. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  80031. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  80032. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  80033. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  80034. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  80035. // VBO
  80036. var vertices = [];
  80037. vertices.push(1, 1);
  80038. vertices.push(-1, 1);
  80039. vertices.push(-1, -1);
  80040. vertices.push(1, -1);
  80041. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80042. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80043. this._createIndexBuffer();
  80044. // Effect
  80045. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  80046. // Render target
  80047. this.setMainTextureSize();
  80048. // Create Textures and post processes
  80049. this.createTextureAndPostProcesses();
  80050. }
  80051. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  80052. /**
  80053. * Gets the horizontal size of the blur.
  80054. */
  80055. get: function () {
  80056. return this._horizontalBlurPostprocess.kernel;
  80057. },
  80058. /**
  80059. * Specifies the horizontal size of the blur.
  80060. */
  80061. set: function (value) {
  80062. this._horizontalBlurPostprocess.kernel = value;
  80063. },
  80064. enumerable: true,
  80065. configurable: true
  80066. });
  80067. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  80068. /**
  80069. * Gets the vertical size of the blur.
  80070. */
  80071. get: function () {
  80072. return this._verticalBlurPostprocess.kernel;
  80073. },
  80074. /**
  80075. * Specifies the vertical size of the blur.
  80076. */
  80077. set: function (value) {
  80078. this._verticalBlurPostprocess.kernel = value;
  80079. },
  80080. enumerable: true,
  80081. configurable: true
  80082. });
  80083. Object.defineProperty(HighlightLayer.prototype, "camera", {
  80084. /**
  80085. * Gets the camera attached to the layer.
  80086. */
  80087. get: function () {
  80088. return this._options.camera;
  80089. },
  80090. enumerable: true,
  80091. configurable: true
  80092. });
  80093. HighlightLayer.prototype._createIndexBuffer = function () {
  80094. var engine = this._scene.getEngine();
  80095. // Indices
  80096. var indices = [];
  80097. indices.push(0);
  80098. indices.push(1);
  80099. indices.push(2);
  80100. indices.push(0);
  80101. indices.push(2);
  80102. indices.push(3);
  80103. this._indexBuffer = engine.createIndexBuffer(indices);
  80104. };
  80105. HighlightLayer.prototype._rebuild = function () {
  80106. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80107. if (vb) {
  80108. vb._rebuild();
  80109. }
  80110. this._createIndexBuffer();
  80111. };
  80112. /**
  80113. * Creates the render target textures and post processes used in the highlight layer.
  80114. */
  80115. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  80116. var _this = this;
  80117. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  80118. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  80119. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  80120. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  80121. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  80122. width: this._mainTextureDesiredSize.width,
  80123. height: this._mainTextureDesiredSize.height
  80124. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80125. this._mainTexture.activeCamera = this._options.camera;
  80126. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80127. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80128. this._mainTexture.anisotropicFilteringLevel = 1;
  80129. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80130. this._mainTexture.renderParticles = false;
  80131. this._mainTexture.renderList = null;
  80132. this._mainTexture.ignoreCameraViewport = true;
  80133. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  80134. width: blurTextureWidth,
  80135. height: blurTextureHeight
  80136. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80137. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80138. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80139. this._blurTexture.anisotropicFilteringLevel = 16;
  80140. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80141. this._blurTexture.renderParticles = false;
  80142. this._blurTexture.ignoreCameraViewport = true;
  80143. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80144. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  80145. effect.setTexture("textureSampler", _this._mainTexture);
  80146. });
  80147. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  80148. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80149. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80150. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80151. });
  80152. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80153. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80154. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80155. });
  80156. }
  80157. else {
  80158. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80159. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80160. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80161. });
  80162. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80163. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80164. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80165. });
  80166. }
  80167. this._mainTexture.onAfterUnbindObservable.add(function () {
  80168. _this.onBeforeBlurObservable.notifyObservers(_this);
  80169. var internalTexture = _this._blurTexture.getInternalTexture();
  80170. if (internalTexture) {
  80171. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  80172. }
  80173. _this.onAfterBlurObservable.notifyObservers(_this);
  80174. });
  80175. // Custom render function
  80176. var renderSubMesh = function (subMesh) {
  80177. if (!_this._meshes) {
  80178. return;
  80179. }
  80180. var material = subMesh.getMaterial();
  80181. var mesh = subMesh.getRenderingMesh();
  80182. var scene = _this._scene;
  80183. var engine = scene.getEngine();
  80184. if (!material) {
  80185. return;
  80186. }
  80187. // Do not block in blend mode.
  80188. if (material.needAlphaBlendingForMesh(mesh)) {
  80189. return;
  80190. }
  80191. // Culling
  80192. engine.setState(material.backFaceCulling);
  80193. // Managing instances
  80194. var batch = mesh._getInstancesRenderList(subMesh._id);
  80195. if (batch.mustReturn) {
  80196. return;
  80197. }
  80198. // Excluded Mesh
  80199. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80200. return;
  80201. }
  80202. ;
  80203. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80204. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  80205. var emissiveTexture = null;
  80206. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80207. emissiveTexture = material.emissiveTexture;
  80208. }
  80209. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  80210. engine.enableEffect(_this._glowMapGenerationEffect);
  80211. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  80212. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  80213. if (highlightLayerMesh) {
  80214. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  80215. }
  80216. else {
  80217. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  80218. }
  80219. // Alpha test
  80220. if (material && material.needAlphaTesting()) {
  80221. var alphaTexture = material.getAlphaTestTexture();
  80222. if (alphaTexture) {
  80223. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  80224. var textureMatrix = alphaTexture.getTextureMatrix();
  80225. if (textureMatrix) {
  80226. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  80227. }
  80228. }
  80229. }
  80230. // Glow emissive only
  80231. if (emissiveTexture) {
  80232. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  80233. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  80234. }
  80235. // Bones
  80236. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80237. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80238. }
  80239. // Draw
  80240. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  80241. }
  80242. else {
  80243. // Need to reset refresh rate of the shadowMap
  80244. _this._mainTexture.resetRefreshCounter();
  80245. }
  80246. };
  80247. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80248. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  80249. var index;
  80250. var engine = _this._scene.getEngine();
  80251. if (depthOnlySubMeshes.length) {
  80252. engine.setColorWrite(false);
  80253. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80254. renderSubMesh(depthOnlySubMeshes.data[index]);
  80255. }
  80256. engine.setColorWrite(true);
  80257. }
  80258. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80259. renderSubMesh(opaqueSubMeshes.data[index]);
  80260. }
  80261. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80262. renderSubMesh(alphaTestSubMeshes.data[index]);
  80263. }
  80264. for (index = 0; index < transparentSubMeshes.length; index++) {
  80265. renderSubMesh(transparentSubMeshes.data[index]);
  80266. }
  80267. };
  80268. this._mainTexture.onClearObservable.add(function (engine) {
  80269. engine.clear(HighlightLayer.neutralColor, true, true, true);
  80270. });
  80271. };
  80272. /**
  80273. * Checks for the readiness of the element composing the layer.
  80274. * @param subMesh the mesh to check for
  80275. * @param useInstances specify wether or not to use instances to render the mesh
  80276. * @param emissiveTexture the associated emissive texture used to generate the glow
  80277. * @return true if ready otherwise, false
  80278. */
  80279. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  80280. var material = subMesh.getMaterial();
  80281. var mesh = subMesh.getRenderingMesh();
  80282. if (!material || !mesh || !this._meshes) {
  80283. return false;
  80284. }
  80285. var emissiveTexture = null;
  80286. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  80287. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80288. emissiveTexture = material.emissiveTexture;
  80289. }
  80290. return this._isReady(subMesh, useInstances, emissiveTexture);
  80291. };
  80292. /**
  80293. * Checks for the readiness of the element composing the layer.
  80294. * @param subMesh the mesh to check for
  80295. * @param useInstances specify wether or not to use instances to render the mesh
  80296. * @param emissiveTexture the associated emissive texture used to generate the glow
  80297. * @return true if ready otherwise, false
  80298. */
  80299. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  80300. var material = subMesh.getMaterial();
  80301. if (!material) {
  80302. return false;
  80303. }
  80304. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  80305. return false;
  80306. }
  80307. var defines = [];
  80308. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80309. var mesh = subMesh.getMesh();
  80310. var uv1 = false;
  80311. var uv2 = false;
  80312. // Alpha test
  80313. if (material && material.needAlphaTesting()) {
  80314. var alphaTexture = material.getAlphaTestTexture();
  80315. if (alphaTexture) {
  80316. defines.push("#define ALPHATEST");
  80317. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80318. alphaTexture.coordinatesIndex === 1) {
  80319. defines.push("#define DIFFUSEUV2");
  80320. uv2 = true;
  80321. }
  80322. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80323. defines.push("#define DIFFUSEUV1");
  80324. uv1 = true;
  80325. }
  80326. }
  80327. }
  80328. // Emissive
  80329. if (emissiveTexture) {
  80330. defines.push("#define EMISSIVE");
  80331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80332. emissiveTexture.coordinatesIndex === 1) {
  80333. defines.push("#define EMISSIVEUV2");
  80334. uv2 = true;
  80335. }
  80336. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80337. defines.push("#define EMISSIVEUV1");
  80338. uv1 = true;
  80339. }
  80340. }
  80341. if (uv1) {
  80342. attribs.push(BABYLON.VertexBuffer.UVKind);
  80343. defines.push("#define UV1");
  80344. }
  80345. if (uv2) {
  80346. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80347. defines.push("#define UV2");
  80348. }
  80349. // Bones
  80350. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80351. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80352. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80353. if (mesh.numBoneInfluencers > 4) {
  80354. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80355. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80356. }
  80357. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80358. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80359. }
  80360. else {
  80361. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80362. }
  80363. // Instances
  80364. if (useInstances) {
  80365. defines.push("#define INSTANCES");
  80366. attribs.push("world0");
  80367. attribs.push("world1");
  80368. attribs.push("world2");
  80369. attribs.push("world3");
  80370. }
  80371. // Get correct effect
  80372. var join = defines.join("\n");
  80373. if (this._cachedDefines !== join) {
  80374. this._cachedDefines = join;
  80375. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  80376. }
  80377. return this._glowMapGenerationEffect.isReady();
  80378. };
  80379. /**
  80380. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  80381. */
  80382. HighlightLayer.prototype.render = function () {
  80383. var currentEffect = this._glowMapMergeEffect;
  80384. // Check
  80385. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  80386. return;
  80387. var engine = this._scene.getEngine();
  80388. this.onBeforeComposeObservable.notifyObservers(this);
  80389. // Render
  80390. engine.enableEffect(currentEffect);
  80391. engine.setState(false);
  80392. // Cache
  80393. var previousStencilBuffer = engine.getStencilBuffer();
  80394. var previousStencilFunction = engine.getStencilFunction();
  80395. var previousStencilMask = engine.getStencilMask();
  80396. var previousStencilOperationPass = engine.getStencilOperationPass();
  80397. var previousStencilOperationFail = engine.getStencilOperationFail();
  80398. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  80399. var previousAlphaMode = engine.getAlphaMode();
  80400. // Texture
  80401. currentEffect.setTexture("textureSampler", this._blurTexture);
  80402. // VBOs
  80403. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80404. // Stencil operations
  80405. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  80406. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  80407. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  80408. // Draw order
  80409. engine.setAlphaMode(this._options.alphaBlendingMode);
  80410. engine.setStencilMask(0x00);
  80411. engine.setStencilBuffer(true);
  80412. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  80413. if (this.outerGlow) {
  80414. currentEffect.setFloat("offset", 0);
  80415. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  80416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80417. }
  80418. if (this.innerGlow) {
  80419. currentEffect.setFloat("offset", 1);
  80420. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  80421. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80422. }
  80423. // Restore Cache
  80424. engine.setStencilFunction(previousStencilFunction);
  80425. engine.setStencilMask(previousStencilMask);
  80426. engine.setAlphaMode(previousAlphaMode);
  80427. engine.setStencilBuffer(previousStencilBuffer);
  80428. engine.setStencilOperationPass(previousStencilOperationPass);
  80429. engine.setStencilOperationFail(previousStencilOperationFail);
  80430. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  80431. engine._stencilState.reset();
  80432. this.onAfterComposeObservable.notifyObservers(this);
  80433. // Handle size changes.
  80434. var size = this._mainTexture.getSize();
  80435. this.setMainTextureSize();
  80436. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  80437. // Recreate RTT and post processes on size change.
  80438. this.onSizeChangedObservable.notifyObservers(this);
  80439. this.disposeTextureAndPostProcesses();
  80440. this.createTextureAndPostProcesses();
  80441. }
  80442. };
  80443. /**
  80444. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  80445. * @param mesh The mesh to exclude from the highlight layer
  80446. */
  80447. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  80448. if (!this._excludedMeshes) {
  80449. return;
  80450. }
  80451. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80452. if (!meshExcluded) {
  80453. this._excludedMeshes[mesh.uniqueId] = {
  80454. mesh: mesh,
  80455. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  80456. mesh.getEngine().setStencilBuffer(false);
  80457. }),
  80458. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  80459. mesh.getEngine().setStencilBuffer(true);
  80460. }),
  80461. };
  80462. }
  80463. };
  80464. /**
  80465. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  80466. * @param mesh The mesh to highlight
  80467. */
  80468. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  80469. if (!this._excludedMeshes) {
  80470. return;
  80471. }
  80472. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80473. if (meshExcluded) {
  80474. if (meshExcluded.beforeRender) {
  80475. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  80476. }
  80477. if (meshExcluded.afterRender) {
  80478. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  80479. }
  80480. }
  80481. this._excludedMeshes[mesh.uniqueId] = null;
  80482. };
  80483. /**
  80484. * Determine if a given mesh will be highlighted by the current HighlightLayer
  80485. * @param mesh mesh to test
  80486. * @returns true if the mesh will be highlighted by the current HighlightLayer
  80487. */
  80488. HighlightLayer.prototype.hasMesh = function (mesh) {
  80489. if (!this._meshes) {
  80490. return false;
  80491. }
  80492. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  80493. };
  80494. /**
  80495. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  80496. * @param mesh The mesh to highlight
  80497. * @param color The color of the highlight
  80498. * @param glowEmissiveOnly Extract the glow from the emissive texture
  80499. */
  80500. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  80501. var _this = this;
  80502. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  80503. if (!this._meshes) {
  80504. return;
  80505. }
  80506. var meshHighlight = this._meshes[mesh.uniqueId];
  80507. if (meshHighlight) {
  80508. meshHighlight.color = color;
  80509. }
  80510. else {
  80511. this._meshes[mesh.uniqueId] = {
  80512. mesh: mesh,
  80513. color: color,
  80514. // Lambda required for capture due to Observable this context
  80515. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  80516. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80517. _this.defaultStencilReference(mesh);
  80518. }
  80519. else {
  80520. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  80521. }
  80522. }),
  80523. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  80524. glowEmissiveOnly: glowEmissiveOnly
  80525. };
  80526. }
  80527. this._shouldRender = true;
  80528. };
  80529. /**
  80530. * Remove a mesh from the highlight layer in order to make it stop glowing.
  80531. * @param mesh The mesh to highlight
  80532. */
  80533. HighlightLayer.prototype.removeMesh = function (mesh) {
  80534. if (!this._meshes) {
  80535. return;
  80536. }
  80537. var meshHighlight = this._meshes[mesh.uniqueId];
  80538. if (meshHighlight) {
  80539. if (meshHighlight.observerHighlight) {
  80540. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80541. }
  80542. if (meshHighlight.observerDefault) {
  80543. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80544. }
  80545. delete this._meshes[mesh.uniqueId];
  80546. }
  80547. this._shouldRender = false;
  80548. for (var meshHighlightToCheck in this._meshes) {
  80549. if (this._meshes[meshHighlightToCheck]) {
  80550. this._shouldRender = true;
  80551. break;
  80552. }
  80553. }
  80554. };
  80555. /**
  80556. * Returns true if the layer contains information to display, otherwise false.
  80557. */
  80558. HighlightLayer.prototype.shouldRender = function () {
  80559. return this.isEnabled && this._shouldRender;
  80560. };
  80561. /**
  80562. * Sets the main texture desired size which is the closest power of two
  80563. * of the engine canvas size.
  80564. */
  80565. HighlightLayer.prototype.setMainTextureSize = function () {
  80566. if (this._options.mainTextureFixedSize) {
  80567. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  80568. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  80569. }
  80570. else {
  80571. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  80572. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  80573. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  80574. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  80575. }
  80576. };
  80577. /**
  80578. * Force the stencil to the normal expected value for none glowing parts
  80579. */
  80580. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  80581. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  80582. };
  80583. /**
  80584. * Dispose only the render target textures and post process.
  80585. */
  80586. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  80587. this._blurTexture.dispose();
  80588. this._mainTexture.dispose();
  80589. this._downSamplePostprocess.dispose();
  80590. this._horizontalBlurPostprocess.dispose();
  80591. this._verticalBlurPostprocess.dispose();
  80592. };
  80593. /**
  80594. * Dispose the highlight layer and free resources.
  80595. */
  80596. HighlightLayer.prototype.dispose = function () {
  80597. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80598. if (vertexBuffer) {
  80599. vertexBuffer.dispose();
  80600. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80601. }
  80602. if (this._indexBuffer) {
  80603. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80604. this._indexBuffer = null;
  80605. }
  80606. // Clean textures and post processes
  80607. this.disposeTextureAndPostProcesses();
  80608. if (this._meshes) {
  80609. // Clean mesh references
  80610. for (var id in this._meshes) {
  80611. var meshHighlight = this._meshes[id];
  80612. if (meshHighlight && meshHighlight.mesh) {
  80613. if (meshHighlight.observerHighlight) {
  80614. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80615. }
  80616. if (meshHighlight.observerDefault) {
  80617. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80618. }
  80619. }
  80620. }
  80621. this._meshes = null;
  80622. }
  80623. if (this._excludedMeshes) {
  80624. for (var id in this._excludedMeshes) {
  80625. var meshHighlight = this._excludedMeshes[id];
  80626. if (meshHighlight) {
  80627. if (meshHighlight.beforeRender) {
  80628. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  80629. }
  80630. if (meshHighlight.afterRender) {
  80631. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  80632. }
  80633. }
  80634. }
  80635. this._excludedMeshes = null;
  80636. }
  80637. // Remove from scene
  80638. var index = this._scene.highlightLayers.indexOf(this, 0);
  80639. if (index > -1) {
  80640. this._scene.highlightLayers.splice(index, 1);
  80641. }
  80642. // Callback
  80643. this.onDisposeObservable.notifyObservers(this);
  80644. this.onDisposeObservable.clear();
  80645. this.onBeforeRenderMainTextureObservable.clear();
  80646. this.onBeforeBlurObservable.clear();
  80647. this.onBeforeComposeObservable.clear();
  80648. this.onAfterComposeObservable.clear();
  80649. this.onSizeChangedObservable.clear();
  80650. };
  80651. /**
  80652. * The neutral color used during the preparation of the glow effect.
  80653. * This is black by default as the blend operation is a blend operation.
  80654. */
  80655. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  80656. /**
  80657. * Stencil value used for glowing meshes.
  80658. */
  80659. HighlightLayer.glowingMeshStencilReference = 0x02;
  80660. /**
  80661. * Stencil value used for the other meshes in the scene.
  80662. */
  80663. HighlightLayer.normalMeshStencilReference = 0x01;
  80664. return HighlightLayer;
  80665. }());
  80666. BABYLON.HighlightLayer = HighlightLayer;
  80667. })(BABYLON || (BABYLON = {}));
  80668. //# sourceMappingURL=babylon.highlightlayer.js.map
  80669. var BABYLON;
  80670. (function (BABYLON) {
  80671. /**
  80672. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  80673. */
  80674. var AssetTaskState;
  80675. (function (AssetTaskState) {
  80676. /**
  80677. * Initialization
  80678. */
  80679. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  80680. /**
  80681. * Running
  80682. */
  80683. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  80684. /**
  80685. * Done
  80686. */
  80687. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  80688. /**
  80689. * Error
  80690. */
  80691. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  80692. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  80693. /**
  80694. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  80695. */
  80696. var AbstractAssetTask = /** @class */ (function () {
  80697. /**
  80698. * Creates a new {BABYLON.AssetsManager}
  80699. * @param name defines the name of the task
  80700. */
  80701. function AbstractAssetTask(
  80702. /**
  80703. * Task name
  80704. */ name) {
  80705. this.name = name;
  80706. this._isCompleted = false;
  80707. this._taskState = AssetTaskState.INIT;
  80708. }
  80709. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  80710. /**
  80711. * Get if the task is completed
  80712. */
  80713. get: function () {
  80714. return this._isCompleted;
  80715. },
  80716. enumerable: true,
  80717. configurable: true
  80718. });
  80719. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  80720. /**
  80721. * Gets the current state of the task
  80722. */
  80723. get: function () {
  80724. return this._taskState;
  80725. },
  80726. enumerable: true,
  80727. configurable: true
  80728. });
  80729. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  80730. /**
  80731. * Gets the current error object (if task is in error)
  80732. */
  80733. get: function () {
  80734. return this._errorObject;
  80735. },
  80736. enumerable: true,
  80737. configurable: true
  80738. });
  80739. /**
  80740. * Internal only
  80741. * @ignore
  80742. */
  80743. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  80744. if (this._errorObject) {
  80745. return;
  80746. }
  80747. this._errorObject = {
  80748. message: message,
  80749. exception: exception
  80750. };
  80751. };
  80752. /**
  80753. * Execute the current task
  80754. * @param scene defines the scene where you want your assets to be loaded
  80755. * @param onSuccess is a callback called when the task is successfully executed
  80756. * @param onError is a callback called if an error occurs
  80757. */
  80758. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80759. var _this = this;
  80760. this._taskState = AssetTaskState.RUNNING;
  80761. this.runTask(scene, function () {
  80762. _this.onDoneCallback(onSuccess, onError);
  80763. }, function (msg, exception) {
  80764. _this.onErrorCallback(onError, msg, exception);
  80765. });
  80766. };
  80767. /**
  80768. * Execute the current task
  80769. * @param scene defines the scene where you want your assets to be loaded
  80770. * @param onSuccess is a callback called when the task is successfully executed
  80771. * @param onError is a callback called if an error occurs
  80772. */
  80773. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80774. throw new Error("runTask is not implemented");
  80775. };
  80776. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  80777. this._taskState = AssetTaskState.ERROR;
  80778. this._errorObject = {
  80779. message: message,
  80780. exception: exception
  80781. };
  80782. if (this.onError) {
  80783. this.onError(this, message, exception);
  80784. }
  80785. onError();
  80786. };
  80787. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  80788. try {
  80789. this._taskState = AssetTaskState.DONE;
  80790. this._isCompleted = true;
  80791. if (this.onSuccess) {
  80792. this.onSuccess(this);
  80793. }
  80794. onSuccess();
  80795. }
  80796. catch (e) {
  80797. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  80798. }
  80799. };
  80800. return AbstractAssetTask;
  80801. }());
  80802. BABYLON.AbstractAssetTask = AbstractAssetTask;
  80803. /**
  80804. * Class used to share progress information about assets loading
  80805. */
  80806. var AssetsProgressEvent = /** @class */ (function () {
  80807. /**
  80808. * Creates a {BABYLON.AssetsProgressEvent}
  80809. * @param remainingCount defines the number of remaining tasks to process
  80810. * @param totalCount defines the total number of tasks
  80811. * @param task defines the task that was just processed
  80812. */
  80813. function AssetsProgressEvent(remainingCount, totalCount, task) {
  80814. this.remainingCount = remainingCount;
  80815. this.totalCount = totalCount;
  80816. this.task = task;
  80817. }
  80818. return AssetsProgressEvent;
  80819. }());
  80820. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  80821. /**
  80822. * Define a task used by {BABYLON.AssetsManager} to load meshes
  80823. */
  80824. var MeshAssetTask = /** @class */ (function (_super) {
  80825. __extends(MeshAssetTask, _super);
  80826. /**
  80827. * Creates a new {BABYLON.MeshAssetTask}
  80828. * @param name defines the name of the task
  80829. * @param meshesNames defines the list of mesh's names you want to load
  80830. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  80831. * @param sceneFilename defines the filename of the scene to load from
  80832. */
  80833. function MeshAssetTask(
  80834. /**
  80835. * Defines the name of the task
  80836. */
  80837. name,
  80838. /**
  80839. * Defines the list of mesh's names you want to load
  80840. */
  80841. meshesNames,
  80842. /**
  80843. * Defines the root url to use as a base to load your meshes and associated resources
  80844. */
  80845. rootUrl,
  80846. /**
  80847. * Defines the filename of the scene to load from
  80848. */
  80849. sceneFilename) {
  80850. var _this = _super.call(this, name) || this;
  80851. _this.name = name;
  80852. _this.meshesNames = meshesNames;
  80853. _this.rootUrl = rootUrl;
  80854. _this.sceneFilename = sceneFilename;
  80855. return _this;
  80856. }
  80857. /**
  80858. * Execute the current task
  80859. * @param scene defines the scene where you want your assets to be loaded
  80860. * @param onSuccess is a callback called when the task is successfully executed
  80861. * @param onError is a callback called if an error occurs
  80862. */
  80863. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80864. var _this = this;
  80865. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  80866. _this.loadedMeshes = meshes;
  80867. _this.loadedParticleSystems = particleSystems;
  80868. _this.loadedSkeletons = skeletons;
  80869. onSuccess();
  80870. }, null, function (scene, message, exception) {
  80871. onError(message, exception);
  80872. });
  80873. };
  80874. return MeshAssetTask;
  80875. }(AbstractAssetTask));
  80876. BABYLON.MeshAssetTask = MeshAssetTask;
  80877. /**
  80878. * Define a task used by {BABYLON.AssetsManager} to load text content
  80879. */
  80880. var TextFileAssetTask = /** @class */ (function (_super) {
  80881. __extends(TextFileAssetTask, _super);
  80882. /**
  80883. * Creates a new TextFileAssetTask object
  80884. * @param name defines the name of the task
  80885. * @param url defines the location of the file to load
  80886. */
  80887. function TextFileAssetTask(
  80888. /**
  80889. * Defines the name of the task
  80890. */
  80891. name,
  80892. /**
  80893. * Defines the location of the file to load
  80894. */
  80895. url) {
  80896. var _this = _super.call(this, name) || this;
  80897. _this.name = name;
  80898. _this.url = url;
  80899. return _this;
  80900. }
  80901. /**
  80902. * Execute the current task
  80903. * @param scene defines the scene where you want your assets to be loaded
  80904. * @param onSuccess is a callback called when the task is successfully executed
  80905. * @param onError is a callback called if an error occurs
  80906. */
  80907. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80908. var _this = this;
  80909. scene._loadFile(this.url, function (data) {
  80910. _this.text = data;
  80911. onSuccess();
  80912. }, undefined, false, true, function (request, exception) {
  80913. if (request) {
  80914. onError(request.status + " " + request.statusText, exception);
  80915. }
  80916. });
  80917. };
  80918. return TextFileAssetTask;
  80919. }(AbstractAssetTask));
  80920. BABYLON.TextFileAssetTask = TextFileAssetTask;
  80921. /**
  80922. * Define a task used by {BABYLON.AssetsManager} to load binary data
  80923. */
  80924. var BinaryFileAssetTask = /** @class */ (function (_super) {
  80925. __extends(BinaryFileAssetTask, _super);
  80926. /**
  80927. * Creates a new BinaryFileAssetTask object
  80928. * @param name defines the name of the new task
  80929. * @param url defines the location of the file to load
  80930. */
  80931. function BinaryFileAssetTask(
  80932. /**
  80933. * Defines the name of the task
  80934. */
  80935. name,
  80936. /**
  80937. * Defines the location of the file to load
  80938. */
  80939. url) {
  80940. var _this = _super.call(this, name) || this;
  80941. _this.name = name;
  80942. _this.url = url;
  80943. return _this;
  80944. }
  80945. /**
  80946. * Execute the current task
  80947. * @param scene defines the scene where you want your assets to be loaded
  80948. * @param onSuccess is a callback called when the task is successfully executed
  80949. * @param onError is a callback called if an error occurs
  80950. */
  80951. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80952. var _this = this;
  80953. scene._loadFile(this.url, function (data) {
  80954. _this.data = data;
  80955. onSuccess();
  80956. }, undefined, true, true, function (request, exception) {
  80957. if (request) {
  80958. onError(request.status + " " + request.statusText, exception);
  80959. }
  80960. });
  80961. };
  80962. return BinaryFileAssetTask;
  80963. }(AbstractAssetTask));
  80964. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  80965. /**
  80966. * Define a task used by {BABYLON.AssetsManager} to load images
  80967. */
  80968. var ImageAssetTask = /** @class */ (function (_super) {
  80969. __extends(ImageAssetTask, _super);
  80970. /**
  80971. * Creates a new ImageAssetTask
  80972. * @param name defines the name of the task
  80973. * @param url defines the location of the image to load
  80974. */
  80975. function ImageAssetTask(
  80976. /**
  80977. * Defines the name of the task
  80978. */
  80979. name,
  80980. /**
  80981. * Defines the location of the image to load
  80982. */
  80983. url) {
  80984. var _this = _super.call(this, name) || this;
  80985. _this.name = name;
  80986. _this.url = url;
  80987. return _this;
  80988. }
  80989. /**
  80990. * Execute the current task
  80991. * @param scene defines the scene where you want your assets to be loaded
  80992. * @param onSuccess is a callback called when the task is successfully executed
  80993. * @param onError is a callback called if an error occurs
  80994. */
  80995. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80996. var _this = this;
  80997. var img = new Image();
  80998. BABYLON.Tools.SetCorsBehavior(this.url, img);
  80999. img.onload = function () {
  81000. _this.image = img;
  81001. onSuccess();
  81002. };
  81003. img.onerror = function (err) {
  81004. onError("Error loading image", err);
  81005. };
  81006. img.src = this.url;
  81007. };
  81008. return ImageAssetTask;
  81009. }(AbstractAssetTask));
  81010. BABYLON.ImageAssetTask = ImageAssetTask;
  81011. /**
  81012. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  81013. */
  81014. var TextureAssetTask = /** @class */ (function (_super) {
  81015. __extends(TextureAssetTask, _super);
  81016. /**
  81017. * Creates a new TextureAssetTask object
  81018. * @param name defines the name of the task
  81019. * @param url defines the location of the file to load
  81020. * @param noMipmap defines if mipmap should not be generated (default is false)
  81021. * @param invertY defines if texture must be inverted on Y axis (default is false)
  81022. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81023. */
  81024. function TextureAssetTask(
  81025. /**
  81026. * Defines the name of the task
  81027. */
  81028. name,
  81029. /**
  81030. * Defines the location of the file to load
  81031. */
  81032. url,
  81033. /**
  81034. * Defines if mipmap should not be generated (default is false)
  81035. */
  81036. noMipmap,
  81037. /**
  81038. * Defines if texture must be inverted on Y axis (default is false)
  81039. */
  81040. invertY,
  81041. /**
  81042. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81043. */
  81044. samplingMode) {
  81045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81046. var _this = _super.call(this, name) || this;
  81047. _this.name = name;
  81048. _this.url = url;
  81049. _this.noMipmap = noMipmap;
  81050. _this.invertY = invertY;
  81051. _this.samplingMode = samplingMode;
  81052. return _this;
  81053. }
  81054. /**
  81055. * Execute the current task
  81056. * @param scene defines the scene where you want your assets to be loaded
  81057. * @param onSuccess is a callback called when the task is successfully executed
  81058. * @param onError is a callback called if an error occurs
  81059. */
  81060. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81061. var onload = function () {
  81062. onSuccess();
  81063. };
  81064. var onerror = function (message, exception) {
  81065. onError(message, exception);
  81066. };
  81067. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  81068. };
  81069. return TextureAssetTask;
  81070. }(AbstractAssetTask));
  81071. BABYLON.TextureAssetTask = TextureAssetTask;
  81072. /**
  81073. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  81074. */
  81075. var CubeTextureAssetTask = /** @class */ (function (_super) {
  81076. __extends(CubeTextureAssetTask, _super);
  81077. /**
  81078. * Creates a new CubeTextureAssetTask
  81079. * @param name defines the name of the task
  81080. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81081. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81082. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81083. * @param files defines the explicit list of files (undefined by default)
  81084. */
  81085. function CubeTextureAssetTask(
  81086. /**
  81087. * Defines the name of the task
  81088. */
  81089. name,
  81090. /**
  81091. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81092. */
  81093. url,
  81094. /**
  81095. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81096. */
  81097. extensions,
  81098. /**
  81099. * Defines if mipmaps should not be generated (default is false)
  81100. */
  81101. noMipmap,
  81102. /**
  81103. * Defines the explicit list of files (undefined by default)
  81104. */
  81105. files) {
  81106. var _this = _super.call(this, name) || this;
  81107. _this.name = name;
  81108. _this.url = url;
  81109. _this.extensions = extensions;
  81110. _this.noMipmap = noMipmap;
  81111. _this.files = files;
  81112. return _this;
  81113. }
  81114. /**
  81115. * Execute the current task
  81116. * @param scene defines the scene where you want your assets to be loaded
  81117. * @param onSuccess is a callback called when the task is successfully executed
  81118. * @param onError is a callback called if an error occurs
  81119. */
  81120. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81121. var onload = function () {
  81122. onSuccess();
  81123. };
  81124. var onerror = function (message, exception) {
  81125. onError(message, exception);
  81126. };
  81127. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  81128. };
  81129. return CubeTextureAssetTask;
  81130. }(AbstractAssetTask));
  81131. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  81132. /**
  81133. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  81134. */
  81135. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  81136. __extends(HDRCubeTextureAssetTask, _super);
  81137. /**
  81138. * Creates a new HDRCubeTextureAssetTask object
  81139. * @param name defines the name of the task
  81140. * @param url defines the location of the file to load
  81141. * @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.
  81142. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81143. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81144. * @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)
  81145. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81146. */
  81147. function HDRCubeTextureAssetTask(
  81148. /**
  81149. * Defines the name of the task
  81150. */
  81151. name,
  81152. /**
  81153. * Defines the location of the file to load
  81154. */
  81155. url,
  81156. /**
  81157. * 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.
  81158. */
  81159. size,
  81160. /**
  81161. * Defines if mipmaps should not be generated (default is false)
  81162. */
  81163. noMipmap,
  81164. /**
  81165. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81166. */
  81167. generateHarmonics,
  81168. /**
  81169. * 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)
  81170. */
  81171. useInGammaSpace,
  81172. /**
  81173. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81174. */
  81175. usePMREMGenerator) {
  81176. if (noMipmap === void 0) { noMipmap = false; }
  81177. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81178. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81179. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81180. var _this = _super.call(this, name) || this;
  81181. _this.name = name;
  81182. _this.url = url;
  81183. _this.size = size;
  81184. _this.noMipmap = noMipmap;
  81185. _this.generateHarmonics = generateHarmonics;
  81186. _this.useInGammaSpace = useInGammaSpace;
  81187. _this.usePMREMGenerator = usePMREMGenerator;
  81188. return _this;
  81189. }
  81190. /**
  81191. * Execute the current task
  81192. * @param scene defines the scene where you want your assets to be loaded
  81193. * @param onSuccess is a callback called when the task is successfully executed
  81194. * @param onError is a callback called if an error occurs
  81195. */
  81196. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81197. var onload = function () {
  81198. onSuccess();
  81199. };
  81200. var onerror = function (message, exception) {
  81201. onError(message, exception);
  81202. };
  81203. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  81204. };
  81205. return HDRCubeTextureAssetTask;
  81206. }(AbstractAssetTask));
  81207. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  81208. /**
  81209. * This class can be used to easily import assets into a scene
  81210. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  81211. */
  81212. var AssetsManager = /** @class */ (function () {
  81213. /**
  81214. * Creates a new AssetsManager
  81215. * @param scene defines the scene to work on
  81216. */
  81217. function AssetsManager(scene) {
  81218. this._isLoading = false;
  81219. this._tasks = new Array();
  81220. this._waitingTasksCount = 0;
  81221. this._totalTasksCount = 0;
  81222. /**
  81223. * Observable called when all tasks are processed
  81224. */
  81225. this.onTaskSuccessObservable = new BABYLON.Observable();
  81226. /**
  81227. * Observable called when a task had an error
  81228. */
  81229. this.onTaskErrorObservable = new BABYLON.Observable();
  81230. /**
  81231. * Observable called when a task is successful
  81232. */
  81233. this.onTasksDoneObservable = new BABYLON.Observable();
  81234. /**
  81235. * Observable called when a task is done (whatever the result is)
  81236. */
  81237. this.onProgressObservable = new BABYLON.Observable();
  81238. /**
  81239. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  81240. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  81241. */
  81242. this.useDefaultLoadingScreen = true;
  81243. this._scene = scene;
  81244. }
  81245. /**
  81246. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  81247. * @param taskName defines the name of the new task
  81248. * @param meshesNames defines the name of meshes to load
  81249. * @param rootUrl defines the root url to use to locate files
  81250. * @param sceneFilename defines the filename of the scene file
  81251. * @returns a new {BABYLON.MeshAssetTask} object
  81252. */
  81253. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  81254. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  81255. this._tasks.push(task);
  81256. return task;
  81257. };
  81258. /**
  81259. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  81260. * @param taskName defines the name of the new task
  81261. * @param url defines the url of the file to load
  81262. * @returns a new {BABYLON.TextFileAssetTask} object
  81263. */
  81264. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  81265. var task = new TextFileAssetTask(taskName, url);
  81266. this._tasks.push(task);
  81267. return task;
  81268. };
  81269. /**
  81270. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  81271. * @param taskName defines the name of the new task
  81272. * @param url defines the url of the file to load
  81273. * @returns a new {BABYLON.BinaryFileAssetTask} object
  81274. */
  81275. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  81276. var task = new BinaryFileAssetTask(taskName, url);
  81277. this._tasks.push(task);
  81278. return task;
  81279. };
  81280. /**
  81281. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  81282. * @param taskName defines the name of the new task
  81283. * @param url defines the url of the file to load
  81284. * @returns a new {BABYLON.ImageAssetTask} object
  81285. */
  81286. AssetsManager.prototype.addImageTask = function (taskName, url) {
  81287. var task = new ImageAssetTask(taskName, url);
  81288. this._tasks.push(task);
  81289. return task;
  81290. };
  81291. /**
  81292. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  81293. * @param taskName defines the name of the new task
  81294. * @param url defines the url of the file to load
  81295. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81296. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  81297. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  81298. * @returns a new {BABYLON.TextureAssetTask} object
  81299. */
  81300. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  81301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81302. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  81303. this._tasks.push(task);
  81304. return task;
  81305. };
  81306. /**
  81307. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  81308. * @param taskName defines the name of the new task
  81309. * @param url defines the url of the file to load
  81310. * @param extensions defines the extension to use to load the cube map (can be null)
  81311. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81312. * @param files defines the list of files to load (can be null)
  81313. * @returns a new {BABYLON.CubeTextureAssetTask} object
  81314. */
  81315. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  81316. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  81317. this._tasks.push(task);
  81318. return task;
  81319. };
  81320. /**
  81321. *
  81322. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  81323. * @param taskName defines the name of the new task
  81324. * @param url defines the url of the file to load
  81325. * @param size defines the size you want for the cubemap (can be null)
  81326. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81327. * @param generateHarmonics defines if you want to automatically generate (true by default)
  81328. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  81329. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  81330. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  81331. */
  81332. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  81333. if (noMipmap === void 0) { noMipmap = false; }
  81334. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81335. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81336. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81337. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  81338. this._tasks.push(task);
  81339. return task;
  81340. };
  81341. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  81342. var _this = this;
  81343. this._waitingTasksCount--;
  81344. try {
  81345. if (task.taskState === AssetTaskState.DONE) {
  81346. // Let's remove successfull tasks
  81347. BABYLON.Tools.SetImmediate(function () {
  81348. var index = _this._tasks.indexOf(task);
  81349. if (index > -1) {
  81350. _this._tasks.splice(index, 1);
  81351. }
  81352. });
  81353. }
  81354. if (this.onProgress) {
  81355. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  81356. }
  81357. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  81358. }
  81359. catch (e) {
  81360. BABYLON.Tools.Error("Error running progress callbacks.");
  81361. console.log(e);
  81362. }
  81363. if (this._waitingTasksCount === 0) {
  81364. try {
  81365. if (this.onFinish) {
  81366. this.onFinish(this._tasks);
  81367. }
  81368. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81369. }
  81370. catch (e) {
  81371. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  81372. console.log(e);
  81373. }
  81374. this._isLoading = false;
  81375. this._scene.getEngine().hideLoadingUI();
  81376. }
  81377. };
  81378. AssetsManager.prototype._runTask = function (task) {
  81379. var _this = this;
  81380. var done = function () {
  81381. try {
  81382. if (_this.onTaskSuccess) {
  81383. _this.onTaskSuccess(task);
  81384. }
  81385. _this.onTaskSuccessObservable.notifyObservers(task);
  81386. _this._decreaseWaitingTasksCount(task);
  81387. }
  81388. catch (e) {
  81389. error("Error executing task success callbacks", e);
  81390. }
  81391. };
  81392. var error = function (message, exception) {
  81393. task._setErrorObject(message, exception);
  81394. if (_this.onTaskError) {
  81395. _this.onTaskError(task);
  81396. }
  81397. _this.onTaskErrorObservable.notifyObservers(task);
  81398. _this._decreaseWaitingTasksCount(task);
  81399. };
  81400. task.run(this._scene, done, error);
  81401. };
  81402. /**
  81403. * Reset the {BABYLON.AssetsManager} and remove all tasks
  81404. * @return the current instance of the {BABYLON.AssetsManager}
  81405. */
  81406. AssetsManager.prototype.reset = function () {
  81407. this._isLoading = false;
  81408. this._tasks = new Array();
  81409. return this;
  81410. };
  81411. /**
  81412. * Start the loading process
  81413. * @return the current instance of the {BABYLON.AssetsManager}
  81414. */
  81415. AssetsManager.prototype.load = function () {
  81416. if (this._isLoading) {
  81417. return this;
  81418. }
  81419. this._isLoading = true;
  81420. this._waitingTasksCount = this._tasks.length;
  81421. this._totalTasksCount = this._tasks.length;
  81422. if (this._waitingTasksCount === 0) {
  81423. if (this.onFinish) {
  81424. this.onFinish(this._tasks);
  81425. }
  81426. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81427. return this;
  81428. }
  81429. if (this.useDefaultLoadingScreen) {
  81430. this._scene.getEngine().displayLoadingUI();
  81431. }
  81432. for (var index = 0; index < this._tasks.length; index++) {
  81433. var task = this._tasks[index];
  81434. this._runTask(task);
  81435. }
  81436. return this;
  81437. };
  81438. return AssetsManager;
  81439. }());
  81440. BABYLON.AssetsManager = AssetsManager;
  81441. })(BABYLON || (BABYLON = {}));
  81442. //# sourceMappingURL=babylon.assetsManager.js.map
  81443. var BABYLON;
  81444. (function (BABYLON) {
  81445. var serializedGeometries = [];
  81446. var serializeGeometry = function (geometry, serializationGeometries) {
  81447. if (serializedGeometries[geometry.id]) {
  81448. return;
  81449. }
  81450. if (geometry.doNotSerialize) {
  81451. return;
  81452. }
  81453. if (geometry instanceof BABYLON.BoxGeometry) {
  81454. serializationGeometries.boxes.push(geometry.serialize());
  81455. }
  81456. else if (geometry instanceof BABYLON.SphereGeometry) {
  81457. serializationGeometries.spheres.push(geometry.serialize());
  81458. }
  81459. else if (geometry instanceof BABYLON.CylinderGeometry) {
  81460. serializationGeometries.cylinders.push(geometry.serialize());
  81461. }
  81462. else if (geometry instanceof BABYLON.TorusGeometry) {
  81463. serializationGeometries.toruses.push(geometry.serialize());
  81464. }
  81465. else if (geometry instanceof BABYLON.GroundGeometry) {
  81466. serializationGeometries.grounds.push(geometry.serialize());
  81467. }
  81468. else if (geometry instanceof BABYLON.Plane) {
  81469. serializationGeometries.planes.push(geometry.serialize());
  81470. }
  81471. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  81472. serializationGeometries.torusKnots.push(geometry.serialize());
  81473. }
  81474. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  81475. throw new Error("Unknown primitive type");
  81476. }
  81477. else {
  81478. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  81479. }
  81480. serializedGeometries[geometry.id] = true;
  81481. };
  81482. var serializeMesh = function (mesh, serializationScene) {
  81483. var serializationObject = {};
  81484. // Geometry
  81485. var geometry = mesh._geometry;
  81486. if (geometry) {
  81487. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  81488. // 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
  81489. serializeGeometry(geometry, serializationScene.geometries);
  81490. }
  81491. }
  81492. // Custom
  81493. if (mesh.serialize) {
  81494. mesh.serialize(serializationObject);
  81495. }
  81496. return serializationObject;
  81497. };
  81498. var finalizeSingleMesh = function (mesh, serializationObject) {
  81499. //only works if the mesh is already loaded
  81500. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81501. //serialize material
  81502. if (mesh.material) {
  81503. if (mesh.material instanceof BABYLON.StandardMaterial) {
  81504. serializationObject.materials = serializationObject.materials || [];
  81505. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81506. serializationObject.materials.push(mesh.material.serialize());
  81507. }
  81508. }
  81509. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  81510. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  81511. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81512. serializationObject.multiMaterials.push(mesh.material.serialize());
  81513. }
  81514. }
  81515. }
  81516. //serialize geometry
  81517. var geometry = mesh._geometry;
  81518. if (geometry) {
  81519. if (!serializationObject.geometries) {
  81520. serializationObject.geometries = {};
  81521. serializationObject.geometries.boxes = [];
  81522. serializationObject.geometries.spheres = [];
  81523. serializationObject.geometries.cylinders = [];
  81524. serializationObject.geometries.toruses = [];
  81525. serializationObject.geometries.grounds = [];
  81526. serializationObject.geometries.planes = [];
  81527. serializationObject.geometries.torusKnots = [];
  81528. serializationObject.geometries.vertexData = [];
  81529. }
  81530. serializeGeometry(geometry, serializationObject.geometries);
  81531. }
  81532. // Skeletons
  81533. if (mesh.skeleton) {
  81534. serializationObject.skeletons = serializationObject.skeletons || [];
  81535. serializationObject.skeletons.push(mesh.skeleton.serialize());
  81536. }
  81537. //serialize the actual mesh
  81538. serializationObject.meshes = serializationObject.meshes || [];
  81539. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81540. }
  81541. };
  81542. var SceneSerializer = /** @class */ (function () {
  81543. function SceneSerializer() {
  81544. }
  81545. SceneSerializer.ClearCache = function () {
  81546. serializedGeometries = [];
  81547. };
  81548. SceneSerializer.Serialize = function (scene) {
  81549. var serializationObject = {};
  81550. SceneSerializer.ClearCache();
  81551. // Scene
  81552. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  81553. serializationObject.autoClear = scene.autoClear;
  81554. serializationObject.clearColor = scene.clearColor.asArray();
  81555. serializationObject.ambientColor = scene.ambientColor.asArray();
  81556. serializationObject.gravity = scene.gravity.asArray();
  81557. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  81558. serializationObject.workerCollisions = scene.workerCollisions;
  81559. // Fog
  81560. if (scene.fogMode && scene.fogMode !== 0) {
  81561. serializationObject.fogMode = scene.fogMode;
  81562. serializationObject.fogColor = scene.fogColor.asArray();
  81563. serializationObject.fogStart = scene.fogStart;
  81564. serializationObject.fogEnd = scene.fogEnd;
  81565. serializationObject.fogDensity = scene.fogDensity;
  81566. }
  81567. //Physics
  81568. if (scene.isPhysicsEnabled()) {
  81569. var physicEngine = scene.getPhysicsEngine();
  81570. if (physicEngine) {
  81571. serializationObject.physicsEnabled = true;
  81572. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  81573. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  81574. }
  81575. }
  81576. // Metadata
  81577. if (scene.metadata) {
  81578. serializationObject.metadata = scene.metadata;
  81579. }
  81580. // Morph targets
  81581. serializationObject.morphTargetManagers = [];
  81582. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  81583. var abstractMesh = _a[_i];
  81584. var manager = abstractMesh.morphTargetManager;
  81585. if (manager) {
  81586. serializationObject.morphTargetManagers.push(manager.serialize());
  81587. }
  81588. }
  81589. // Lights
  81590. serializationObject.lights = [];
  81591. var index;
  81592. var light;
  81593. for (index = 0; index < scene.lights.length; index++) {
  81594. light = scene.lights[index];
  81595. if (!light.doNotSerialize) {
  81596. serializationObject.lights.push(light.serialize());
  81597. }
  81598. }
  81599. // Cameras
  81600. serializationObject.cameras = [];
  81601. for (index = 0; index < scene.cameras.length; index++) {
  81602. var camera = scene.cameras[index];
  81603. if (!camera.doNotSerialize) {
  81604. serializationObject.cameras.push(camera.serialize());
  81605. }
  81606. }
  81607. if (scene.activeCamera) {
  81608. serializationObject.activeCameraID = scene.activeCamera.id;
  81609. }
  81610. // Animations
  81611. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  81612. // Materials
  81613. serializationObject.materials = [];
  81614. serializationObject.multiMaterials = [];
  81615. var material;
  81616. for (index = 0; index < scene.materials.length; index++) {
  81617. material = scene.materials[index];
  81618. if (!material.doNotSerialize) {
  81619. serializationObject.materials.push(material.serialize());
  81620. }
  81621. }
  81622. // MultiMaterials
  81623. serializationObject.multiMaterials = [];
  81624. for (index = 0; index < scene.multiMaterials.length; index++) {
  81625. var multiMaterial = scene.multiMaterials[index];
  81626. serializationObject.multiMaterials.push(multiMaterial.serialize());
  81627. }
  81628. // Environment texture
  81629. if (scene.environmentTexture) {
  81630. serializationObject.environmentTexture = scene.environmentTexture.name;
  81631. }
  81632. // Skeletons
  81633. serializationObject.skeletons = [];
  81634. for (index = 0; index < scene.skeletons.length; index++) {
  81635. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  81636. }
  81637. // Transform nodes
  81638. serializationObject.transformNodes = [];
  81639. for (index = 0; index < scene.transformNodes.length; index++) {
  81640. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  81641. }
  81642. // Geometries
  81643. serializationObject.geometries = {};
  81644. serializationObject.geometries.boxes = [];
  81645. serializationObject.geometries.spheres = [];
  81646. serializationObject.geometries.cylinders = [];
  81647. serializationObject.geometries.toruses = [];
  81648. serializationObject.geometries.grounds = [];
  81649. serializationObject.geometries.planes = [];
  81650. serializationObject.geometries.torusKnots = [];
  81651. serializationObject.geometries.vertexData = [];
  81652. serializedGeometries = [];
  81653. var geometries = scene.getGeometries();
  81654. for (index = 0; index < geometries.length; index++) {
  81655. var geometry = geometries[index];
  81656. if (geometry.isReady()) {
  81657. serializeGeometry(geometry, serializationObject.geometries);
  81658. }
  81659. }
  81660. // Meshes
  81661. serializationObject.meshes = [];
  81662. for (index = 0; index < scene.meshes.length; index++) {
  81663. var abstractMesh = scene.meshes[index];
  81664. if (abstractMesh instanceof BABYLON.Mesh) {
  81665. var mesh = abstractMesh;
  81666. if (!mesh.doNotSerialize) {
  81667. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81668. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81669. }
  81670. }
  81671. }
  81672. }
  81673. // Particles Systems
  81674. serializationObject.particleSystems = [];
  81675. for (index = 0; index < scene.particleSystems.length; index++) {
  81676. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  81677. }
  81678. // Lens flares
  81679. serializationObject.lensFlareSystems = [];
  81680. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  81681. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  81682. }
  81683. // Shadows
  81684. serializationObject.shadowGenerators = [];
  81685. for (index = 0; index < scene.lights.length; index++) {
  81686. light = scene.lights[index];
  81687. var shadowGenerator = light.getShadowGenerator();
  81688. if (shadowGenerator) {
  81689. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  81690. }
  81691. }
  81692. // Action Manager
  81693. if (scene.actionManager) {
  81694. serializationObject.actions = scene.actionManager.serialize("scene");
  81695. }
  81696. // Audio
  81697. serializationObject.sounds = [];
  81698. for (index = 0; index < scene.soundTracks.length; index++) {
  81699. var soundtrack = scene.soundTracks[index];
  81700. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  81701. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  81702. }
  81703. }
  81704. return serializationObject;
  81705. };
  81706. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  81707. if (withParents === void 0) { withParents = false; }
  81708. if (withChildren === void 0) { withChildren = false; }
  81709. var serializationObject = {};
  81710. SceneSerializer.ClearCache();
  81711. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  81712. if (withParents || withChildren) {
  81713. //deliberate for loop! not for each, appended should be processed as well.
  81714. for (var i = 0; i < toSerialize.length; ++i) {
  81715. if (withChildren) {
  81716. toSerialize[i].getDescendants().forEach(function (node) {
  81717. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  81718. toSerialize.push(node);
  81719. }
  81720. });
  81721. }
  81722. //make sure the array doesn't contain the object already
  81723. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  81724. toSerialize.push(toSerialize[i].parent);
  81725. }
  81726. }
  81727. }
  81728. toSerialize.forEach(function (mesh) {
  81729. finalizeSingleMesh(mesh, serializationObject);
  81730. });
  81731. return serializationObject;
  81732. };
  81733. return SceneSerializer;
  81734. }());
  81735. BABYLON.SceneSerializer = SceneSerializer;
  81736. })(BABYLON || (BABYLON = {}));
  81737. //# sourceMappingURL=babylon.sceneSerializer.js.map
  81738. var BABYLON;
  81739. (function (BABYLON) {
  81740. var ReflectionProbe = /** @class */ (function () {
  81741. function ReflectionProbe(name, size, scene, generateMipMaps) {
  81742. if (generateMipMaps === void 0) { generateMipMaps = true; }
  81743. var _this = this;
  81744. this.name = name;
  81745. this._viewMatrix = BABYLON.Matrix.Identity();
  81746. this._target = BABYLON.Vector3.Zero();
  81747. this._add = BABYLON.Vector3.Zero();
  81748. this.invertYAxis = false;
  81749. this.position = BABYLON.Vector3.Zero();
  81750. this._scene = scene;
  81751. this._scene.reflectionProbes.push(this);
  81752. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  81753. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  81754. switch (faceIndex) {
  81755. case 0:
  81756. _this._add.copyFromFloats(1, 0, 0);
  81757. break;
  81758. case 1:
  81759. _this._add.copyFromFloats(-1, 0, 0);
  81760. break;
  81761. case 2:
  81762. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  81763. break;
  81764. case 3:
  81765. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  81766. break;
  81767. case 4:
  81768. _this._add.copyFromFloats(0, 0, 1);
  81769. break;
  81770. case 5:
  81771. _this._add.copyFromFloats(0, 0, -1);
  81772. break;
  81773. }
  81774. if (_this._attachedMesh) {
  81775. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  81776. }
  81777. _this.position.addToRef(_this._add, _this._target);
  81778. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  81779. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  81780. scene._forcedViewPosition = _this.position;
  81781. });
  81782. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  81783. scene._forcedViewPosition = null;
  81784. scene.updateTransformMatrix(true);
  81785. });
  81786. if (scene.activeCamera) {
  81787. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  81788. }
  81789. }
  81790. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  81791. get: function () {
  81792. return this._renderTargetTexture.samples;
  81793. },
  81794. set: function (value) {
  81795. this._renderTargetTexture.samples = value;
  81796. },
  81797. enumerable: true,
  81798. configurable: true
  81799. });
  81800. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  81801. get: function () {
  81802. return this._renderTargetTexture.refreshRate;
  81803. },
  81804. set: function (value) {
  81805. this._renderTargetTexture.refreshRate = value;
  81806. },
  81807. enumerable: true,
  81808. configurable: true
  81809. });
  81810. ReflectionProbe.prototype.getScene = function () {
  81811. return this._scene;
  81812. };
  81813. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  81814. get: function () {
  81815. return this._renderTargetTexture;
  81816. },
  81817. enumerable: true,
  81818. configurable: true
  81819. });
  81820. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  81821. get: function () {
  81822. return this._renderTargetTexture.renderList;
  81823. },
  81824. enumerable: true,
  81825. configurable: true
  81826. });
  81827. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  81828. this._attachedMesh = mesh;
  81829. };
  81830. /**
  81831. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  81832. *
  81833. * @param renderingGroupId The rendering group id corresponding to its index
  81834. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  81835. */
  81836. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  81837. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  81838. };
  81839. ReflectionProbe.prototype.dispose = function () {
  81840. var index = this._scene.reflectionProbes.indexOf(this);
  81841. if (index !== -1) {
  81842. // Remove from the scene if found
  81843. this._scene.reflectionProbes.splice(index, 1);
  81844. }
  81845. if (this._renderTargetTexture) {
  81846. this._renderTargetTexture.dispose();
  81847. this._renderTargetTexture = null;
  81848. }
  81849. };
  81850. return ReflectionProbe;
  81851. }());
  81852. BABYLON.ReflectionProbe = ReflectionProbe;
  81853. })(BABYLON || (BABYLON = {}));
  81854. //# sourceMappingURL=babylon.reflectionProbe.js.map
  81855. var BABYLON;
  81856. (function (BABYLON) {
  81857. var Layer = /** @class */ (function () {
  81858. function Layer(name, imgUrl, scene, isBackground, color) {
  81859. this.name = name;
  81860. this.scale = new BABYLON.Vector2(1, 1);
  81861. this.offset = new BABYLON.Vector2(0, 0);
  81862. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  81863. this.layerMask = 0x0FFFFFFF;
  81864. this._vertexBuffers = {};
  81865. // Events
  81866. /**
  81867. * An event triggered when the layer is disposed.
  81868. * @type {BABYLON.Observable}
  81869. */
  81870. this.onDisposeObservable = new BABYLON.Observable();
  81871. /**
  81872. * An event triggered before rendering the scene
  81873. * @type {BABYLON.Observable}
  81874. */
  81875. this.onBeforeRenderObservable = new BABYLON.Observable();
  81876. /**
  81877. * An event triggered after rendering the scene
  81878. * @type {BABYLON.Observable}
  81879. */
  81880. this.onAfterRenderObservable = new BABYLON.Observable();
  81881. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  81882. this.isBackground = isBackground === undefined ? true : isBackground;
  81883. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  81884. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  81885. this._scene.layers.push(this);
  81886. var engine = this._scene.getEngine();
  81887. // VBO
  81888. var vertices = [];
  81889. vertices.push(1, 1);
  81890. vertices.push(-1, 1);
  81891. vertices.push(-1, -1);
  81892. vertices.push(1, -1);
  81893. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81894. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81895. this._createIndexBuffer();
  81896. // Effects
  81897. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  81898. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  81899. }
  81900. Object.defineProperty(Layer.prototype, "onDispose", {
  81901. set: function (callback) {
  81902. if (this._onDisposeObserver) {
  81903. this.onDisposeObservable.remove(this._onDisposeObserver);
  81904. }
  81905. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81906. },
  81907. enumerable: true,
  81908. configurable: true
  81909. });
  81910. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  81911. set: function (callback) {
  81912. if (this._onBeforeRenderObserver) {
  81913. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  81914. }
  81915. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  81916. },
  81917. enumerable: true,
  81918. configurable: true
  81919. });
  81920. Object.defineProperty(Layer.prototype, "onAfterRender", {
  81921. set: function (callback) {
  81922. if (this._onAfterRenderObserver) {
  81923. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  81924. }
  81925. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  81926. },
  81927. enumerable: true,
  81928. configurable: true
  81929. });
  81930. Layer.prototype._createIndexBuffer = function () {
  81931. var engine = this._scene.getEngine();
  81932. // Indices
  81933. var indices = [];
  81934. indices.push(0);
  81935. indices.push(1);
  81936. indices.push(2);
  81937. indices.push(0);
  81938. indices.push(2);
  81939. indices.push(3);
  81940. this._indexBuffer = engine.createIndexBuffer(indices);
  81941. };
  81942. Layer.prototype._rebuild = function () {
  81943. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81944. if (vb) {
  81945. vb._rebuild();
  81946. }
  81947. this._createIndexBuffer();
  81948. };
  81949. Layer.prototype.render = function () {
  81950. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  81951. // Check
  81952. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  81953. return;
  81954. var engine = this._scene.getEngine();
  81955. this.onBeforeRenderObservable.notifyObservers(this);
  81956. // Render
  81957. engine.enableEffect(currentEffect);
  81958. engine.setState(false);
  81959. // Texture
  81960. currentEffect.setTexture("textureSampler", this.texture);
  81961. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  81962. // Color
  81963. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  81964. // Scale / offset
  81965. currentEffect.setVector2("offset", this.offset);
  81966. currentEffect.setVector2("scale", this.scale);
  81967. // VBOs
  81968. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81969. // Draw order
  81970. if (!this.alphaTest) {
  81971. engine.setAlphaMode(this.alphaBlendingMode);
  81972. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81973. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81974. }
  81975. else {
  81976. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81977. }
  81978. this.onAfterRenderObservable.notifyObservers(this);
  81979. };
  81980. Layer.prototype.dispose = function () {
  81981. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81982. if (vertexBuffer) {
  81983. vertexBuffer.dispose();
  81984. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81985. }
  81986. if (this._indexBuffer) {
  81987. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81988. this._indexBuffer = null;
  81989. }
  81990. if (this.texture) {
  81991. this.texture.dispose();
  81992. this.texture = null;
  81993. }
  81994. // Remove from scene
  81995. var index = this._scene.layers.indexOf(this);
  81996. this._scene.layers.splice(index, 1);
  81997. // Callback
  81998. this.onDisposeObservable.notifyObservers(this);
  81999. this.onDisposeObservable.clear();
  82000. this.onAfterRenderObservable.clear();
  82001. this.onBeforeRenderObservable.clear();
  82002. };
  82003. return Layer;
  82004. }());
  82005. BABYLON.Layer = Layer;
  82006. })(BABYLON || (BABYLON = {}));
  82007. //# sourceMappingURL=babylon.layer.js.map
  82008. var BABYLON;
  82009. (function (BABYLON) {
  82010. var TextureTools = /** @class */ (function () {
  82011. function TextureTools() {
  82012. }
  82013. /**
  82014. * Uses the GPU to create a copy texture rescaled at a given size
  82015. * @param texture Texture to copy from
  82016. * @param width Desired width
  82017. * @param height Desired height
  82018. * @return Generated texture
  82019. */
  82020. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  82021. if (useBilinearMode === void 0) { useBilinearMode = true; }
  82022. var scene = texture.getScene();
  82023. var engine = scene.getEngine();
  82024. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  82025. rtt.wrapU = texture.wrapU;
  82026. rtt.wrapV = texture.wrapV;
  82027. rtt.uOffset = texture.uOffset;
  82028. rtt.vOffset = texture.vOffset;
  82029. rtt.uScale = texture.uScale;
  82030. rtt.vScale = texture.vScale;
  82031. rtt.uAng = texture.uAng;
  82032. rtt.vAng = texture.vAng;
  82033. rtt.wAng = texture.wAng;
  82034. rtt.coordinatesIndex = texture.coordinatesIndex;
  82035. rtt.level = texture.level;
  82036. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  82037. rtt._texture.isReady = false;
  82038. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82039. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82040. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82041. passPostProcess.getEffect().executeWhenCompiled(function () {
  82042. passPostProcess.onApply = function (effect) {
  82043. effect.setTexture("textureSampler", texture);
  82044. };
  82045. var internalTexture = rtt.getInternalTexture();
  82046. if (internalTexture) {
  82047. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  82048. engine.unBindFramebuffer(internalTexture);
  82049. rtt.disposeFramebufferObjects();
  82050. passPostProcess.dispose();
  82051. internalTexture.isReady = true;
  82052. }
  82053. });
  82054. return rtt;
  82055. };
  82056. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  82057. if (!scene._environmentBRDFTexture) {
  82058. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82059. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82060. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82061. scene._environmentBRDFTexture = texture;
  82062. }
  82063. return scene._environmentBRDFTexture;
  82064. };
  82065. 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=";
  82066. return TextureTools;
  82067. }());
  82068. BABYLON.TextureTools = TextureTools;
  82069. })(BABYLON || (BABYLON = {}));
  82070. //# sourceMappingURL=babylon.textureTools.js.map
  82071. var BABYLON;
  82072. (function (BABYLON) {
  82073. var FramingBehavior = /** @class */ (function () {
  82074. function FramingBehavior() {
  82075. this._mode = FramingBehavior.FitFrustumSidesMode;
  82076. this._radiusScale = 1.0;
  82077. this._positionScale = 0.5;
  82078. this._defaultElevation = 0.3;
  82079. this._elevationReturnTime = 1500;
  82080. this._elevationReturnWaitTime = 1000;
  82081. this._zoomStopsAnimation = false;
  82082. this._framingTime = 1500;
  82083. this._isPointerDown = false;
  82084. this._lastInteractionTime = -Infinity;
  82085. // Framing control
  82086. this._animatables = new Array();
  82087. this._betaIsAnimating = false;
  82088. }
  82089. Object.defineProperty(FramingBehavior.prototype, "name", {
  82090. get: function () {
  82091. return "Framing";
  82092. },
  82093. enumerable: true,
  82094. configurable: true
  82095. });
  82096. Object.defineProperty(FramingBehavior.prototype, "mode", {
  82097. /**
  82098. * Gets current mode used by the behavior.
  82099. */
  82100. get: function () {
  82101. return this._mode;
  82102. },
  82103. /**
  82104. * Sets the current mode used by the behavior
  82105. */
  82106. set: function (mode) {
  82107. this._mode = mode;
  82108. },
  82109. enumerable: true,
  82110. configurable: true
  82111. });
  82112. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  82113. /**
  82114. * Gets the scale applied to the radius
  82115. */
  82116. get: function () {
  82117. return this._radiusScale;
  82118. },
  82119. /**
  82120. * Sets the scale applied to the radius (1 by default)
  82121. */
  82122. set: function (radius) {
  82123. this._radiusScale = radius;
  82124. },
  82125. enumerable: true,
  82126. configurable: true
  82127. });
  82128. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  82129. /**
  82130. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82131. */
  82132. get: function () {
  82133. return this._positionScale;
  82134. },
  82135. /**
  82136. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82137. */
  82138. set: function (scale) {
  82139. this._positionScale = scale;
  82140. },
  82141. enumerable: true,
  82142. configurable: true
  82143. });
  82144. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  82145. /**
  82146. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82147. * behaviour is triggered, in radians.
  82148. */
  82149. get: function () {
  82150. return this._defaultElevation;
  82151. },
  82152. /**
  82153. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82154. * behaviour is triggered, in radians.
  82155. */
  82156. set: function (elevation) {
  82157. this._defaultElevation = elevation;
  82158. },
  82159. enumerable: true,
  82160. configurable: true
  82161. });
  82162. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  82163. /**
  82164. * Gets the time (in milliseconds) taken to return to the default beta position.
  82165. * Negative value indicates camera should not return to default.
  82166. */
  82167. get: function () {
  82168. return this._elevationReturnTime;
  82169. },
  82170. /**
  82171. * Sets the time (in milliseconds) taken to return to the default beta position.
  82172. * Negative value indicates camera should not return to default.
  82173. */
  82174. set: function (speed) {
  82175. this._elevationReturnTime = speed;
  82176. },
  82177. enumerable: true,
  82178. configurable: true
  82179. });
  82180. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  82181. /**
  82182. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82183. */
  82184. get: function () {
  82185. return this._elevationReturnWaitTime;
  82186. },
  82187. /**
  82188. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82189. */
  82190. set: function (time) {
  82191. this._elevationReturnWaitTime = time;
  82192. },
  82193. enumerable: true,
  82194. configurable: true
  82195. });
  82196. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  82197. /**
  82198. * Gets the flag that indicates if user zooming should stop animation.
  82199. */
  82200. get: function () {
  82201. return this._zoomStopsAnimation;
  82202. },
  82203. /**
  82204. * Sets the flag that indicates if user zooming should stop animation.
  82205. */
  82206. set: function (flag) {
  82207. this._zoomStopsAnimation = flag;
  82208. },
  82209. enumerable: true,
  82210. configurable: true
  82211. });
  82212. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  82213. /**
  82214. * Gets the transition time when framing the mesh, in milliseconds
  82215. */
  82216. get: function () {
  82217. return this._framingTime;
  82218. },
  82219. /**
  82220. * Sets the transition time when framing the mesh, in milliseconds
  82221. */
  82222. set: function (time) {
  82223. this._framingTime = time;
  82224. },
  82225. enumerable: true,
  82226. configurable: true
  82227. });
  82228. FramingBehavior.prototype.init = function () {
  82229. // Do notihng
  82230. };
  82231. FramingBehavior.prototype.attach = function (camera) {
  82232. var _this = this;
  82233. this._attachedCamera = camera;
  82234. var scene = this._attachedCamera.getScene();
  82235. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  82236. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82237. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82238. _this._isPointerDown = true;
  82239. return;
  82240. }
  82241. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82242. _this._isPointerDown = false;
  82243. }
  82244. });
  82245. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82246. if (mesh) {
  82247. _this.zoomOnMesh(mesh);
  82248. }
  82249. });
  82250. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82251. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82252. _this._applyUserInteraction();
  82253. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  82254. // back to the default position after a given timeout
  82255. _this._maintainCameraAboveGround();
  82256. });
  82257. };
  82258. FramingBehavior.prototype.detach = function () {
  82259. if (!this._attachedCamera) {
  82260. return;
  82261. }
  82262. var scene = this._attachedCamera.getScene();
  82263. if (this._onPrePointerObservableObserver) {
  82264. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82265. }
  82266. if (this._onAfterCheckInputsObserver) {
  82267. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82268. }
  82269. if (this._onMeshTargetChangedObserver) {
  82270. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82271. }
  82272. this._attachedCamera = null;
  82273. };
  82274. /**
  82275. * Targets the given mesh and updates zoom level accordingly.
  82276. * @param mesh The mesh to target.
  82277. * @param radius Optional. If a cached radius position already exists, overrides default.
  82278. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82279. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82280. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82281. */
  82282. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82283. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82284. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82285. mesh.computeWorldMatrix(true);
  82286. var boundingBox = mesh.getBoundingInfo().boundingBox;
  82287. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  82288. };
  82289. /**
  82290. * Targets the given mesh with its children and updates zoom level accordingly.
  82291. * @param mesh The mesh to target.
  82292. * @param radius Optional. If a cached radius position already exists, overrides default.
  82293. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82294. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82295. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82296. */
  82297. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82298. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82299. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82300. mesh.computeWorldMatrix(true);
  82301. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  82302. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  82303. };
  82304. /**
  82305. * Targets the given meshes with their children and updates zoom level accordingly.
  82306. * @param meshes The mesh to target.
  82307. * @param radius Optional. If a cached radius position already exists, overrides default.
  82308. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82309. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82310. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82311. */
  82312. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  82313. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82314. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82315. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  82316. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82317. for (var i = 0; i < meshes.length; i++) {
  82318. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  82319. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  82320. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  82321. }
  82322. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  82323. };
  82324. /**
  82325. * Targets the given mesh and updates zoom level accordingly.
  82326. * @param mesh The mesh to target.
  82327. * @param radius Optional. If a cached radius position already exists, overrides default.
  82328. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82329. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82330. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82331. */
  82332. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  82333. var _this = this;
  82334. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82335. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82336. var zoomTarget;
  82337. if (!this._attachedCamera) {
  82338. return;
  82339. }
  82340. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  82341. var bottom = minimumWorld.y;
  82342. var top = maximumWorld.y;
  82343. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  82344. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  82345. if (focusOnOriginXZ) {
  82346. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  82347. }
  82348. else {
  82349. var centerWorld = minimumWorld.add(radiusWorld);
  82350. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  82351. }
  82352. if (!this._vectorTransition) {
  82353. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  82354. }
  82355. this._betaIsAnimating = true;
  82356. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  82357. if (animatable) {
  82358. this._animatables.push(animatable);
  82359. }
  82360. // sets the radius and lower radius bounds
  82361. // Small delta ensures camera is not always at lower zoom limit.
  82362. var radius = 0;
  82363. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  82364. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82365. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  82366. radius = position;
  82367. }
  82368. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82369. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82370. if (this._attachedCamera.lowerRadiusLimit === null) {
  82371. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  82372. }
  82373. }
  82374. // Set sensibilities
  82375. var extend = maximumWorld.subtract(minimumWorld).length();
  82376. this._attachedCamera.panningSensibility = 5000 / extend;
  82377. this._attachedCamera.wheelPrecision = 100 / radius;
  82378. // transition to new radius
  82379. if (!this._radiusTransition) {
  82380. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82381. }
  82382. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  82383. if (onAnimationEnd) {
  82384. onAnimationEnd();
  82385. }
  82386. if (_this._attachedCamera) {
  82387. _this._attachedCamera.storeState();
  82388. }
  82389. });
  82390. if (animatable) {
  82391. this._animatables.push(animatable);
  82392. }
  82393. };
  82394. /**
  82395. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  82396. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  82397. * frustum width.
  82398. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  82399. * to fully enclose the mesh in the viewing frustum.
  82400. */
  82401. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  82402. var size = maximumWorld.subtract(minimumWorld);
  82403. var boxVectorGlobalDiagonal = size.length();
  82404. var frustumSlope = this._getFrustumSlope();
  82405. // Formula for setting distance
  82406. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  82407. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  82408. // Horizon distance
  82409. var radius = radiusWithoutFraming * this._radiusScale;
  82410. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  82411. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  82412. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  82413. var camera = this._attachedCamera;
  82414. if (!camera) {
  82415. return 0;
  82416. }
  82417. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82418. // Don't exceed the requested limit
  82419. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  82420. }
  82421. // Don't exceed the upper radius limit
  82422. if (camera.upperRadiusLimit) {
  82423. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  82424. }
  82425. return distance;
  82426. };
  82427. /**
  82428. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  82429. * is automatically returned to its default position (expected to be above ground plane).
  82430. */
  82431. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  82432. var _this = this;
  82433. if (this._elevationReturnTime < 0) {
  82434. return;
  82435. }
  82436. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  82437. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  82438. var limitBeta = Math.PI * 0.5;
  82439. // Bring the camera back up if below the ground plane
  82440. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  82441. this._betaIsAnimating = true;
  82442. //Transition to new position
  82443. this.stopAllAnimations();
  82444. if (!this._betaTransition) {
  82445. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82446. }
  82447. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  82448. _this._clearAnimationLocks();
  82449. _this.stopAllAnimations();
  82450. });
  82451. if (animatabe) {
  82452. this._animatables.push(animatabe);
  82453. }
  82454. }
  82455. };
  82456. /**
  82457. * Returns the frustum slope based on the canvas ratio and camera FOV
  82458. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  82459. */
  82460. FramingBehavior.prototype._getFrustumSlope = function () {
  82461. // Calculate the viewport ratio
  82462. // Aspect Ratio is Height/Width.
  82463. var camera = this._attachedCamera;
  82464. if (!camera) {
  82465. return BABYLON.Vector2.Zero();
  82466. }
  82467. var engine = camera.getScene().getEngine();
  82468. var aspectRatio = engine.getAspectRatio(camera);
  82469. // Camera FOV is the vertical field of view (top-bottom) in radians.
  82470. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  82471. var frustumSlopeY = Math.tan(camera.fov / 2);
  82472. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  82473. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  82474. // along the forward vector.
  82475. var frustumSlopeX = frustumSlopeY * aspectRatio;
  82476. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  82477. };
  82478. /**
  82479. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  82480. */
  82481. FramingBehavior.prototype._clearAnimationLocks = function () {
  82482. this._betaIsAnimating = false;
  82483. };
  82484. /**
  82485. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82486. */
  82487. FramingBehavior.prototype._applyUserInteraction = function () {
  82488. if (this.isUserIsMoving) {
  82489. this._lastInteractionTime = BABYLON.Tools.Now;
  82490. this.stopAllAnimations();
  82491. this._clearAnimationLocks();
  82492. }
  82493. };
  82494. /**
  82495. * Stops and removes all animations that have been applied to the camera
  82496. */
  82497. FramingBehavior.prototype.stopAllAnimations = function () {
  82498. if (this._attachedCamera) {
  82499. this._attachedCamera.animations = [];
  82500. }
  82501. while (this._animatables.length) {
  82502. if (this._animatables[0]) {
  82503. this._animatables[0].onAnimationEnd = null;
  82504. this._animatables[0].stop();
  82505. }
  82506. this._animatables.shift();
  82507. }
  82508. };
  82509. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  82510. /**
  82511. * Gets a value indicating if the user is moving the camera
  82512. */
  82513. get: function () {
  82514. if (!this._attachedCamera) {
  82515. return false;
  82516. }
  82517. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82518. this._attachedCamera.inertialBetaOffset !== 0 ||
  82519. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82520. this._attachedCamera.inertialPanningX !== 0 ||
  82521. this._attachedCamera.inertialPanningY !== 0 ||
  82522. this._isPointerDown;
  82523. },
  82524. enumerable: true,
  82525. configurable: true
  82526. });
  82527. /**
  82528. * The easing function used by animations
  82529. */
  82530. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  82531. /**
  82532. * The easing mode used by animations
  82533. */
  82534. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  82535. // Statics
  82536. /**
  82537. * The camera can move all the way towards the mesh.
  82538. */
  82539. FramingBehavior.IgnoreBoundsSizeMode = 0;
  82540. /**
  82541. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  82542. */
  82543. FramingBehavior.FitFrustumSidesMode = 1;
  82544. return FramingBehavior;
  82545. }());
  82546. BABYLON.FramingBehavior = FramingBehavior;
  82547. })(BABYLON || (BABYLON = {}));
  82548. //# sourceMappingURL=babylon.framingBehavior.js.map
  82549. var BABYLON;
  82550. (function (BABYLON) {
  82551. /**
  82552. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  82553. */
  82554. var BouncingBehavior = /** @class */ (function () {
  82555. function BouncingBehavior() {
  82556. /**
  82557. * The duration of the animation, in milliseconds
  82558. */
  82559. this.transitionDuration = 450;
  82560. /**
  82561. * Length of the distance animated by the transition when lower radius is reached
  82562. */
  82563. this.lowerRadiusTransitionRange = 2;
  82564. /**
  82565. * Length of the distance animated by the transition when upper radius is reached
  82566. */
  82567. this.upperRadiusTransitionRange = -2;
  82568. this._autoTransitionRange = false;
  82569. // Animations
  82570. this._radiusIsAnimating = false;
  82571. this._radiusBounceTransition = null;
  82572. this._animatables = new Array();
  82573. }
  82574. Object.defineProperty(BouncingBehavior.prototype, "name", {
  82575. get: function () {
  82576. return "Bouncing";
  82577. },
  82578. enumerable: true,
  82579. configurable: true
  82580. });
  82581. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  82582. /**
  82583. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82584. */
  82585. get: function () {
  82586. return this._autoTransitionRange;
  82587. },
  82588. /**
  82589. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82590. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  82591. */
  82592. set: function (value) {
  82593. var _this = this;
  82594. if (this._autoTransitionRange === value) {
  82595. return;
  82596. }
  82597. this._autoTransitionRange = value;
  82598. var camera = this._attachedCamera;
  82599. if (!camera) {
  82600. return;
  82601. }
  82602. if (value) {
  82603. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82604. if (!mesh) {
  82605. return;
  82606. }
  82607. mesh.computeWorldMatrix(true);
  82608. var diagonal = mesh.getBoundingInfo().diagonalLength;
  82609. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  82610. _this.upperRadiusTransitionRange = diagonal * 0.05;
  82611. });
  82612. }
  82613. else if (this._onMeshTargetChangedObserver) {
  82614. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82615. }
  82616. },
  82617. enumerable: true,
  82618. configurable: true
  82619. });
  82620. BouncingBehavior.prototype.init = function () {
  82621. // Do notihng
  82622. };
  82623. BouncingBehavior.prototype.attach = function (camera) {
  82624. var _this = this;
  82625. this._attachedCamera = camera;
  82626. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82627. if (!_this._attachedCamera) {
  82628. return;
  82629. }
  82630. // Add the bounce animation to the lower radius limit
  82631. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  82632. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  82633. }
  82634. // Add the bounce animation to the upper radius limit
  82635. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  82636. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  82637. }
  82638. });
  82639. };
  82640. BouncingBehavior.prototype.detach = function () {
  82641. if (!this._attachedCamera) {
  82642. return;
  82643. }
  82644. if (this._onAfterCheckInputsObserver) {
  82645. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82646. }
  82647. if (this._onMeshTargetChangedObserver) {
  82648. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82649. }
  82650. this._attachedCamera = null;
  82651. };
  82652. /**
  82653. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  82654. * @param radiusLimit The limit to check against.
  82655. * @return Bool to indicate if at limit.
  82656. */
  82657. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  82658. if (!this._attachedCamera) {
  82659. return false;
  82660. }
  82661. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  82662. return true;
  82663. }
  82664. return false;
  82665. };
  82666. /**
  82667. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  82668. * @param radiusDelta The delta by which to animate to. Can be negative.
  82669. */
  82670. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  82671. var _this = this;
  82672. if (!this._attachedCamera) {
  82673. return;
  82674. }
  82675. if (!this._radiusBounceTransition) {
  82676. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  82677. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  82678. }
  82679. // Prevent zoom until bounce has completed
  82680. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  82681. this._attachedCamera.wheelPrecision = Infinity;
  82682. this._attachedCamera.inertialRadiusOffset = 0;
  82683. // Animate to the radius limit
  82684. this.stopAllAnimations();
  82685. this._radiusIsAnimating = true;
  82686. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  82687. if (animatable) {
  82688. this._animatables.push(animatable);
  82689. }
  82690. };
  82691. /**
  82692. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  82693. */
  82694. BouncingBehavior.prototype._clearAnimationLocks = function () {
  82695. this._radiusIsAnimating = false;
  82696. if (this._attachedCamera) {
  82697. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  82698. }
  82699. };
  82700. /**
  82701. * Stops and removes all animations that have been applied to the camera
  82702. */
  82703. BouncingBehavior.prototype.stopAllAnimations = function () {
  82704. if (this._attachedCamera) {
  82705. this._attachedCamera.animations = [];
  82706. }
  82707. while (this._animatables.length) {
  82708. this._animatables[0].onAnimationEnd = null;
  82709. this._animatables[0].stop();
  82710. this._animatables.shift();
  82711. }
  82712. };
  82713. /**
  82714. * The easing function used by animations
  82715. */
  82716. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  82717. /**
  82718. * The easing mode used by animations
  82719. */
  82720. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  82721. return BouncingBehavior;
  82722. }());
  82723. BABYLON.BouncingBehavior = BouncingBehavior;
  82724. })(BABYLON || (BABYLON = {}));
  82725. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  82726. var BABYLON;
  82727. (function (BABYLON) {
  82728. var AutoRotationBehavior = /** @class */ (function () {
  82729. function AutoRotationBehavior() {
  82730. this._zoomStopsAnimation = false;
  82731. this._idleRotationSpeed = 0.05;
  82732. this._idleRotationWaitTime = 2000;
  82733. this._idleRotationSpinupTime = 2000;
  82734. this._isPointerDown = false;
  82735. this._lastFrameTime = null;
  82736. this._lastInteractionTime = -Infinity;
  82737. this._cameraRotationSpeed = 0;
  82738. this._lastFrameRadius = 0;
  82739. }
  82740. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  82741. get: function () {
  82742. return "AutoRotation";
  82743. },
  82744. enumerable: true,
  82745. configurable: true
  82746. });
  82747. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  82748. /**
  82749. * Gets the flag that indicates if user zooming should stop animation.
  82750. */
  82751. get: function () {
  82752. return this._zoomStopsAnimation;
  82753. },
  82754. /**
  82755. * Sets the flag that indicates if user zooming should stop animation.
  82756. */
  82757. set: function (flag) {
  82758. this._zoomStopsAnimation = flag;
  82759. },
  82760. enumerable: true,
  82761. configurable: true
  82762. });
  82763. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  82764. /**
  82765. * Gets the default speed at which the camera rotates around the model.
  82766. */
  82767. get: function () {
  82768. return this._idleRotationSpeed;
  82769. },
  82770. /**
  82771. * Sets the default speed at which the camera rotates around the model.
  82772. */
  82773. set: function (speed) {
  82774. this._idleRotationSpeed = speed;
  82775. },
  82776. enumerable: true,
  82777. configurable: true
  82778. });
  82779. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  82780. /**
  82781. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  82782. */
  82783. get: function () {
  82784. return this._idleRotationWaitTime;
  82785. },
  82786. /**
  82787. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  82788. */
  82789. set: function (time) {
  82790. this._idleRotationWaitTime = time;
  82791. },
  82792. enumerable: true,
  82793. configurable: true
  82794. });
  82795. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  82796. /**
  82797. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82798. */
  82799. get: function () {
  82800. return this._idleRotationSpinupTime;
  82801. },
  82802. /**
  82803. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82804. */
  82805. set: function (time) {
  82806. this._idleRotationSpinupTime = time;
  82807. },
  82808. enumerable: true,
  82809. configurable: true
  82810. });
  82811. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  82812. /**
  82813. * Gets a value indicating if the camera is currently rotating because of this behavior
  82814. */
  82815. get: function () {
  82816. return Math.abs(this._cameraRotationSpeed) > 0;
  82817. },
  82818. enumerable: true,
  82819. configurable: true
  82820. });
  82821. AutoRotationBehavior.prototype.init = function () {
  82822. // Do notihng
  82823. };
  82824. AutoRotationBehavior.prototype.attach = function (camera) {
  82825. var _this = this;
  82826. this._attachedCamera = camera;
  82827. var scene = this._attachedCamera.getScene();
  82828. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82829. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82830. _this._isPointerDown = true;
  82831. return;
  82832. }
  82833. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82834. _this._isPointerDown = false;
  82835. }
  82836. });
  82837. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82838. var now = BABYLON.Tools.Now;
  82839. var dt = 0;
  82840. if (_this._lastFrameTime != null) {
  82841. dt = now - _this._lastFrameTime;
  82842. }
  82843. _this._lastFrameTime = now;
  82844. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82845. _this._applyUserInteraction();
  82846. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  82847. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  82848. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  82849. // Step camera rotation by rotation speed
  82850. if (_this._attachedCamera) {
  82851. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  82852. }
  82853. });
  82854. };
  82855. AutoRotationBehavior.prototype.detach = function () {
  82856. if (!this._attachedCamera) {
  82857. return;
  82858. }
  82859. var scene = this._attachedCamera.getScene();
  82860. if (this._onPrePointerObservableObserver) {
  82861. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82862. }
  82863. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82864. this._attachedCamera = null;
  82865. };
  82866. /**
  82867. * Returns true if user is scrolling.
  82868. * @return true if user is scrolling.
  82869. */
  82870. AutoRotationBehavior.prototype._userIsZooming = function () {
  82871. if (!this._attachedCamera) {
  82872. return false;
  82873. }
  82874. return this._attachedCamera.inertialRadiusOffset !== 0;
  82875. };
  82876. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  82877. if (!this._attachedCamera) {
  82878. return false;
  82879. }
  82880. var zoomHasHitLimit = false;
  82881. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  82882. zoomHasHitLimit = true;
  82883. }
  82884. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  82885. this._lastFrameRadius = this._attachedCamera.radius;
  82886. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  82887. };
  82888. /**
  82889. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82890. */
  82891. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  82892. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  82893. this._lastInteractionTime = BABYLON.Tools.Now;
  82894. }
  82895. };
  82896. // Tools
  82897. AutoRotationBehavior.prototype._userIsMoving = function () {
  82898. if (!this._attachedCamera) {
  82899. return false;
  82900. }
  82901. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82902. this._attachedCamera.inertialBetaOffset !== 0 ||
  82903. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82904. this._attachedCamera.inertialPanningX !== 0 ||
  82905. this._attachedCamera.inertialPanningY !== 0 ||
  82906. this._isPointerDown;
  82907. };
  82908. return AutoRotationBehavior;
  82909. }());
  82910. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  82911. })(BABYLON || (BABYLON = {}));
  82912. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  82913. var BABYLON;
  82914. (function (BABYLON) {
  82915. /**
  82916. * This class can be used to get instrumentation data from a Babylon engine
  82917. */
  82918. var EngineInstrumentation = /** @class */ (function () {
  82919. function EngineInstrumentation(engine) {
  82920. this.engine = engine;
  82921. this._captureGPUFrameTime = false;
  82922. this._gpuFrameTime = new BABYLON.PerfCounter();
  82923. this._captureShaderCompilationTime = false;
  82924. this._shaderCompilationTime = new BABYLON.PerfCounter();
  82925. // Observers
  82926. this._onBeginFrameObserver = null;
  82927. this._onEndFrameObserver = null;
  82928. this._onBeforeShaderCompilationObserver = null;
  82929. this._onAfterShaderCompilationObserver = null;
  82930. }
  82931. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  82932. // Properties
  82933. /**
  82934. * Gets the perf counter used for GPU frame time
  82935. */
  82936. get: function () {
  82937. return this._gpuFrameTime;
  82938. },
  82939. enumerable: true,
  82940. configurable: true
  82941. });
  82942. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  82943. /**
  82944. * Gets the GPU frame time capture status
  82945. */
  82946. get: function () {
  82947. return this._captureGPUFrameTime;
  82948. },
  82949. /**
  82950. * Enable or disable the GPU frame time capture
  82951. */
  82952. set: function (value) {
  82953. var _this = this;
  82954. if (value === this._captureGPUFrameTime) {
  82955. return;
  82956. }
  82957. this._captureGPUFrameTime = value;
  82958. if (value) {
  82959. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  82960. if (!_this._gpuFrameTimeToken) {
  82961. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  82962. }
  82963. });
  82964. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  82965. if (!_this._gpuFrameTimeToken) {
  82966. return;
  82967. }
  82968. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  82969. if (time > -1) {
  82970. _this._gpuFrameTimeToken = null;
  82971. _this._gpuFrameTime.fetchNewFrame();
  82972. _this._gpuFrameTime.addCount(time, true);
  82973. }
  82974. });
  82975. }
  82976. else {
  82977. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82978. this._onBeginFrameObserver = null;
  82979. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82980. this._onEndFrameObserver = null;
  82981. }
  82982. },
  82983. enumerable: true,
  82984. configurable: true
  82985. });
  82986. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  82987. /**
  82988. * Gets the perf counter used for shader compilation time
  82989. */
  82990. get: function () {
  82991. return this._shaderCompilationTime;
  82992. },
  82993. enumerable: true,
  82994. configurable: true
  82995. });
  82996. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  82997. /**
  82998. * Gets the shader compilation time capture status
  82999. */
  83000. get: function () {
  83001. return this._captureShaderCompilationTime;
  83002. },
  83003. /**
  83004. * Enable or disable the shader compilation time capture
  83005. */
  83006. set: function (value) {
  83007. var _this = this;
  83008. if (value === this._captureShaderCompilationTime) {
  83009. return;
  83010. }
  83011. this._captureShaderCompilationTime = value;
  83012. if (value) {
  83013. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  83014. _this._shaderCompilationTime.fetchNewFrame();
  83015. _this._shaderCompilationTime.beginMonitoring();
  83016. });
  83017. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  83018. _this._shaderCompilationTime.endMonitoring();
  83019. });
  83020. }
  83021. else {
  83022. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83023. this._onBeforeShaderCompilationObserver = null;
  83024. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83025. this._onAfterShaderCompilationObserver = null;
  83026. }
  83027. },
  83028. enumerable: true,
  83029. configurable: true
  83030. });
  83031. EngineInstrumentation.prototype.dispose = function () {
  83032. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83033. this._onBeginFrameObserver = null;
  83034. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83035. this._onEndFrameObserver = null;
  83036. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83037. this._onBeforeShaderCompilationObserver = null;
  83038. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83039. this._onAfterShaderCompilationObserver = null;
  83040. this.engine = null;
  83041. };
  83042. return EngineInstrumentation;
  83043. }());
  83044. BABYLON.EngineInstrumentation = EngineInstrumentation;
  83045. })(BABYLON || (BABYLON = {}));
  83046. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  83047. var BABYLON;
  83048. (function (BABYLON) {
  83049. /**
  83050. * This class can be used to get instrumentation data from a Babylon engine
  83051. */
  83052. var SceneInstrumentation = /** @class */ (function () {
  83053. function SceneInstrumentation(scene) {
  83054. var _this = this;
  83055. this.scene = scene;
  83056. this._captureActiveMeshesEvaluationTime = false;
  83057. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  83058. this._captureRenderTargetsRenderTime = false;
  83059. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  83060. this._captureFrameTime = false;
  83061. this._frameTime = new BABYLON.PerfCounter();
  83062. this._captureRenderTime = false;
  83063. this._renderTime = new BABYLON.PerfCounter();
  83064. this._captureInterFrameTime = false;
  83065. this._interFrameTime = new BABYLON.PerfCounter();
  83066. this._captureParticlesRenderTime = false;
  83067. this._particlesRenderTime = new BABYLON.PerfCounter();
  83068. this._captureSpritesRenderTime = false;
  83069. this._spritesRenderTime = new BABYLON.PerfCounter();
  83070. this._capturePhysicsTime = false;
  83071. this._physicsTime = new BABYLON.PerfCounter();
  83072. this._captureAnimationsTime = false;
  83073. this._animationsTime = new BABYLON.PerfCounter();
  83074. // Observers
  83075. this._onBeforeActiveMeshesEvaluationObserver = null;
  83076. this._onAfterActiveMeshesEvaluationObserver = null;
  83077. this._onBeforeRenderTargetsRenderObserver = null;
  83078. this._onAfterRenderTargetsRenderObserver = null;
  83079. this._onAfterRenderObserver = null;
  83080. this._onBeforeDrawPhaseObserver = null;
  83081. this._onAfterDrawPhaseObserver = null;
  83082. this._onBeforeAnimationsObserver = null;
  83083. this._onBeforeParticlesRenderingObserver = null;
  83084. this._onAfterParticlesRenderingObserver = null;
  83085. this._onBeforeSpritesRenderingObserver = null;
  83086. this._onAfterSpritesRenderingObserver = null;
  83087. this._onBeforePhysicsObserver = null;
  83088. this._onAfterPhysicsObserver = null;
  83089. this._onAfterAnimationsObserver = null;
  83090. // Before render
  83091. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  83092. if (_this._captureActiveMeshesEvaluationTime) {
  83093. _this._activeMeshesEvaluationTime.fetchNewFrame();
  83094. }
  83095. if (_this._captureRenderTargetsRenderTime) {
  83096. _this._renderTargetsRenderTime.fetchNewFrame();
  83097. }
  83098. if (_this._captureFrameTime) {
  83099. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  83100. _this._frameTime.beginMonitoring();
  83101. }
  83102. if (_this._captureInterFrameTime) {
  83103. _this._interFrameTime.endMonitoring();
  83104. }
  83105. if (_this._captureParticlesRenderTime) {
  83106. _this._particlesRenderTime.fetchNewFrame();
  83107. }
  83108. if (_this._captureSpritesRenderTime) {
  83109. _this._spritesRenderTime.fetchNewFrame();
  83110. }
  83111. if (_this._captureAnimationsTime) {
  83112. _this._animationsTime.beginMonitoring();
  83113. }
  83114. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  83115. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  83116. });
  83117. // After render
  83118. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  83119. if (_this._captureFrameTime) {
  83120. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  83121. _this._frameTime.endMonitoring();
  83122. }
  83123. if (_this._captureRenderTime) {
  83124. _this._renderTime.endMonitoring(false);
  83125. }
  83126. if (_this._captureInterFrameTime) {
  83127. _this._interFrameTime.beginMonitoring();
  83128. }
  83129. });
  83130. }
  83131. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  83132. // Properties
  83133. /**
  83134. * Gets the perf counter used for active meshes evaluation time
  83135. */
  83136. get: function () {
  83137. return this._activeMeshesEvaluationTime;
  83138. },
  83139. enumerable: true,
  83140. configurable: true
  83141. });
  83142. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  83143. /**
  83144. * Gets the active meshes evaluation time capture status
  83145. */
  83146. get: function () {
  83147. return this._captureActiveMeshesEvaluationTime;
  83148. },
  83149. /**
  83150. * Enable or disable the active meshes evaluation time capture
  83151. */
  83152. set: function (value) {
  83153. var _this = this;
  83154. if (value === this._captureActiveMeshesEvaluationTime) {
  83155. return;
  83156. }
  83157. this._captureActiveMeshesEvaluationTime = value;
  83158. if (value) {
  83159. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  83160. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  83161. _this._activeMeshesEvaluationTime.beginMonitoring();
  83162. });
  83163. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  83164. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  83165. _this._activeMeshesEvaluationTime.endMonitoring();
  83166. });
  83167. }
  83168. else {
  83169. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83170. this._onBeforeActiveMeshesEvaluationObserver = null;
  83171. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83172. this._onAfterActiveMeshesEvaluationObserver = null;
  83173. }
  83174. },
  83175. enumerable: true,
  83176. configurable: true
  83177. });
  83178. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  83179. /**
  83180. * Gets the perf counter used for render targets render time
  83181. */
  83182. get: function () {
  83183. return this._renderTargetsRenderTime;
  83184. },
  83185. enumerable: true,
  83186. configurable: true
  83187. });
  83188. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  83189. /**
  83190. * Gets the render targets render time capture status
  83191. */
  83192. get: function () {
  83193. return this._captureRenderTargetsRenderTime;
  83194. },
  83195. /**
  83196. * Enable or disable the render targets render time capture
  83197. */
  83198. set: function (value) {
  83199. var _this = this;
  83200. if (value === this._captureRenderTargetsRenderTime) {
  83201. return;
  83202. }
  83203. this._captureRenderTargetsRenderTime = value;
  83204. if (value) {
  83205. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  83206. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  83207. _this._renderTargetsRenderTime.beginMonitoring();
  83208. });
  83209. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  83210. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  83211. _this._renderTargetsRenderTime.endMonitoring(false);
  83212. });
  83213. }
  83214. else {
  83215. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83216. this._onBeforeRenderTargetsRenderObserver = null;
  83217. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83218. this._onAfterRenderTargetsRenderObserver = null;
  83219. }
  83220. },
  83221. enumerable: true,
  83222. configurable: true
  83223. });
  83224. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  83225. /**
  83226. * Gets the perf counter used for particles render time
  83227. */
  83228. get: function () {
  83229. return this._particlesRenderTime;
  83230. },
  83231. enumerable: true,
  83232. configurable: true
  83233. });
  83234. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  83235. /**
  83236. * Gets the particles render time capture status
  83237. */
  83238. get: function () {
  83239. return this._captureParticlesRenderTime;
  83240. },
  83241. /**
  83242. * Enable or disable the particles render time capture
  83243. */
  83244. set: function (value) {
  83245. var _this = this;
  83246. if (value === this._captureParticlesRenderTime) {
  83247. return;
  83248. }
  83249. this._captureParticlesRenderTime = value;
  83250. if (value) {
  83251. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  83252. BABYLON.Tools.StartPerformanceCounter("Particles");
  83253. _this._particlesRenderTime.beginMonitoring();
  83254. });
  83255. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  83256. BABYLON.Tools.EndPerformanceCounter("Particles");
  83257. _this._particlesRenderTime.endMonitoring(false);
  83258. });
  83259. }
  83260. else {
  83261. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83262. this._onBeforeParticlesRenderingObserver = null;
  83263. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83264. this._onAfterParticlesRenderingObserver = null;
  83265. }
  83266. },
  83267. enumerable: true,
  83268. configurable: true
  83269. });
  83270. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  83271. /**
  83272. * Gets the perf counter used for sprites render time
  83273. */
  83274. get: function () {
  83275. return this._spritesRenderTime;
  83276. },
  83277. enumerable: true,
  83278. configurable: true
  83279. });
  83280. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  83281. /**
  83282. * Gets the sprites render time capture status
  83283. */
  83284. get: function () {
  83285. return this._captureSpritesRenderTime;
  83286. },
  83287. /**
  83288. * Enable or disable the sprites render time capture
  83289. */
  83290. set: function (value) {
  83291. var _this = this;
  83292. if (value === this._captureSpritesRenderTime) {
  83293. return;
  83294. }
  83295. this._captureSpritesRenderTime = value;
  83296. if (value) {
  83297. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  83298. BABYLON.Tools.StartPerformanceCounter("Sprites");
  83299. _this._spritesRenderTime.beginMonitoring();
  83300. });
  83301. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  83302. BABYLON.Tools.EndPerformanceCounter("Sprites");
  83303. _this._spritesRenderTime.endMonitoring(false);
  83304. });
  83305. }
  83306. else {
  83307. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83308. this._onBeforeSpritesRenderingObserver = null;
  83309. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83310. this._onAfterSpritesRenderingObserver = null;
  83311. }
  83312. },
  83313. enumerable: true,
  83314. configurable: true
  83315. });
  83316. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  83317. /**
  83318. * Gets the perf counter used for physics time
  83319. */
  83320. get: function () {
  83321. return this._physicsTime;
  83322. },
  83323. enumerable: true,
  83324. configurable: true
  83325. });
  83326. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  83327. /**
  83328. * Gets the physics time capture status
  83329. */
  83330. get: function () {
  83331. return this._capturePhysicsTime;
  83332. },
  83333. /**
  83334. * Enable or disable the physics time capture
  83335. */
  83336. set: function (value) {
  83337. var _this = this;
  83338. if (value === this._capturePhysicsTime) {
  83339. return;
  83340. }
  83341. this._capturePhysicsTime = value;
  83342. if (value) {
  83343. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  83344. BABYLON.Tools.StartPerformanceCounter("Physics");
  83345. _this._physicsTime.beginMonitoring();
  83346. });
  83347. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  83348. BABYLON.Tools.EndPerformanceCounter("Physics");
  83349. _this._physicsTime.endMonitoring();
  83350. });
  83351. }
  83352. else {
  83353. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83354. this._onBeforePhysicsObserver = null;
  83355. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83356. this._onAfterPhysicsObserver = null;
  83357. }
  83358. },
  83359. enumerable: true,
  83360. configurable: true
  83361. });
  83362. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  83363. /**
  83364. * Gets the perf counter used for animations time
  83365. */
  83366. get: function () {
  83367. return this._animationsTime;
  83368. },
  83369. enumerable: true,
  83370. configurable: true
  83371. });
  83372. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  83373. /**
  83374. * Gets the animations time capture status
  83375. */
  83376. get: function () {
  83377. return this._captureAnimationsTime;
  83378. },
  83379. /**
  83380. * Enable or disable the animations time capture
  83381. */
  83382. set: function (value) {
  83383. var _this = this;
  83384. if (value === this._captureAnimationsTime) {
  83385. return;
  83386. }
  83387. this._captureAnimationsTime = value;
  83388. if (value) {
  83389. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  83390. _this._animationsTime.endMonitoring();
  83391. });
  83392. }
  83393. else {
  83394. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83395. this._onAfterAnimationsObserver = null;
  83396. }
  83397. },
  83398. enumerable: true,
  83399. configurable: true
  83400. });
  83401. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  83402. /**
  83403. * Gets the perf counter used for frame time capture
  83404. */
  83405. get: function () {
  83406. return this._frameTime;
  83407. },
  83408. enumerable: true,
  83409. configurable: true
  83410. });
  83411. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  83412. /**
  83413. * Gets the frame time capture status
  83414. */
  83415. get: function () {
  83416. return this._captureFrameTime;
  83417. },
  83418. /**
  83419. * Enable or disable the frame time capture
  83420. */
  83421. set: function (value) {
  83422. this._captureFrameTime = value;
  83423. },
  83424. enumerable: true,
  83425. configurable: true
  83426. });
  83427. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  83428. /**
  83429. * Gets the perf counter used for inter-frames time capture
  83430. */
  83431. get: function () {
  83432. return this._interFrameTime;
  83433. },
  83434. enumerable: true,
  83435. configurable: true
  83436. });
  83437. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  83438. /**
  83439. * Gets the inter-frames time capture status
  83440. */
  83441. get: function () {
  83442. return this._captureInterFrameTime;
  83443. },
  83444. /**
  83445. * Enable or disable the inter-frames time capture
  83446. */
  83447. set: function (value) {
  83448. this._captureInterFrameTime = value;
  83449. },
  83450. enumerable: true,
  83451. configurable: true
  83452. });
  83453. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  83454. /**
  83455. * Gets the perf counter used for render time capture
  83456. */
  83457. get: function () {
  83458. return this._renderTime;
  83459. },
  83460. enumerable: true,
  83461. configurable: true
  83462. });
  83463. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  83464. /**
  83465. * Gets the render time capture status
  83466. */
  83467. get: function () {
  83468. return this._captureRenderTime;
  83469. },
  83470. /**
  83471. * Enable or disable the render time capture
  83472. */
  83473. set: function (value) {
  83474. var _this = this;
  83475. if (value === this._captureRenderTime) {
  83476. return;
  83477. }
  83478. this._captureRenderTime = value;
  83479. if (value) {
  83480. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  83481. _this._renderTime.beginMonitoring();
  83482. BABYLON.Tools.StartPerformanceCounter("Main render");
  83483. });
  83484. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  83485. _this._renderTime.endMonitoring(false);
  83486. BABYLON.Tools.EndPerformanceCounter("Main render");
  83487. });
  83488. }
  83489. else {
  83490. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83491. this._onBeforeDrawPhaseObserver = null;
  83492. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83493. this._onAfterDrawPhaseObserver = null;
  83494. }
  83495. },
  83496. enumerable: true,
  83497. configurable: true
  83498. });
  83499. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  83500. /**
  83501. * Gets the perf counter used for draw calls
  83502. */
  83503. get: function () {
  83504. return this.scene.getEngine()._drawCalls;
  83505. },
  83506. enumerable: true,
  83507. configurable: true
  83508. });
  83509. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  83510. /**
  83511. * Gets the perf counter used for texture collisions
  83512. */
  83513. get: function () {
  83514. return this.scene.getEngine()._textureCollisions;
  83515. },
  83516. enumerable: true,
  83517. configurable: true
  83518. });
  83519. SceneInstrumentation.prototype.dispose = function () {
  83520. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83521. this._onAfterRenderObserver = null;
  83522. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83523. this._onBeforeActiveMeshesEvaluationObserver = null;
  83524. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83525. this._onAfterActiveMeshesEvaluationObserver = null;
  83526. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83527. this._onBeforeRenderTargetsRenderObserver = null;
  83528. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83529. this._onAfterRenderTargetsRenderObserver = null;
  83530. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  83531. this._onBeforeAnimationsObserver = null;
  83532. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83533. this._onBeforeParticlesRenderingObserver = null;
  83534. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83535. this._onAfterParticlesRenderingObserver = null;
  83536. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83537. this._onBeforeSpritesRenderingObserver = null;
  83538. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83539. this._onAfterSpritesRenderingObserver = null;
  83540. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83541. this._onBeforeDrawPhaseObserver = null;
  83542. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83543. this._onAfterDrawPhaseObserver = null;
  83544. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83545. this._onBeforePhysicsObserver = null;
  83546. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83547. this._onAfterPhysicsObserver = null;
  83548. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83549. this._onAfterAnimationsObserver = null;
  83550. this.scene = null;
  83551. };
  83552. return SceneInstrumentation;
  83553. }());
  83554. BABYLON.SceneInstrumentation = SceneInstrumentation;
  83555. })(BABYLON || (BABYLON = {}));
  83556. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  83557. var BABYLON;
  83558. (function (BABYLON) {
  83559. var _TimeToken = /** @class */ (function () {
  83560. function _TimeToken() {
  83561. this._timeElapsedQueryEnded = false;
  83562. }
  83563. return _TimeToken;
  83564. }());
  83565. BABYLON._TimeToken = _TimeToken;
  83566. })(BABYLON || (BABYLON = {}));
  83567. //# sourceMappingURL=babylon.timeToken.js.map
  83568. var BABYLON;
  83569. (function (BABYLON) {
  83570. /**
  83571. * Background material defines definition.
  83572. * @ignore Mainly internal Use
  83573. */
  83574. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  83575. __extends(BackgroundMaterialDefines, _super);
  83576. /**
  83577. * Constructor of the defines.
  83578. */
  83579. function BackgroundMaterialDefines() {
  83580. var _this = _super.call(this) || this;
  83581. /**
  83582. * True if the diffuse texture is in use.
  83583. */
  83584. _this.DIFFUSE = false;
  83585. /**
  83586. * The direct UV channel to use.
  83587. */
  83588. _this.DIFFUSEDIRECTUV = 0;
  83589. /**
  83590. * True if the diffuse texture is in gamma space.
  83591. */
  83592. _this.GAMMADIFFUSE = false;
  83593. /**
  83594. * True if the diffuse texture has opacity in the alpha channel.
  83595. */
  83596. _this.DIFFUSEHASALPHA = false;
  83597. /**
  83598. * True if you want the material to fade to transparent at grazing angle.
  83599. */
  83600. _this.OPACITYFRESNEL = false;
  83601. /**
  83602. * True if an extra blur needs to be added in the reflection.
  83603. */
  83604. _this.REFLECTIONBLUR = false;
  83605. /**
  83606. * True if you want the material to fade to reflection at grazing angle.
  83607. */
  83608. _this.REFLECTIONFRESNEL = false;
  83609. /**
  83610. * True if you want the material to falloff as far as you move away from the scene center.
  83611. */
  83612. _this.REFLECTIONFALLOFF = false;
  83613. /**
  83614. * False if the current Webgl implementation does not support the texture lod extension.
  83615. */
  83616. _this.TEXTURELODSUPPORT = false;
  83617. /**
  83618. * True to ensure the data are premultiplied.
  83619. */
  83620. _this.PREMULTIPLYALPHA = false;
  83621. /**
  83622. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  83623. */
  83624. _this.USERGBCOLOR = false;
  83625. /**
  83626. * True to add noise in order to reduce the banding effect.
  83627. */
  83628. _this.NOISE = false;
  83629. // Image Processing Configuration.
  83630. _this.IMAGEPROCESSING = false;
  83631. _this.VIGNETTE = false;
  83632. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83633. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83634. _this.TONEMAPPING = false;
  83635. _this.CONTRAST = false;
  83636. _this.COLORCURVES = false;
  83637. _this.COLORGRADING = false;
  83638. _this.COLORGRADING3D = false;
  83639. _this.SAMPLER3DGREENDEPTH = false;
  83640. _this.SAMPLER3DBGRMAP = false;
  83641. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83642. _this.EXPOSURE = false;
  83643. // Reflection.
  83644. _this.REFLECTION = false;
  83645. _this.REFLECTIONMAP_3D = false;
  83646. _this.REFLECTIONMAP_SPHERICAL = false;
  83647. _this.REFLECTIONMAP_PLANAR = false;
  83648. _this.REFLECTIONMAP_CUBIC = false;
  83649. _this.REFLECTIONMAP_PROJECTION = false;
  83650. _this.REFLECTIONMAP_SKYBOX = false;
  83651. _this.REFLECTIONMAP_EXPLICIT = false;
  83652. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83653. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83654. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83655. _this.INVERTCUBICMAP = false;
  83656. _this.REFLECTIONMAP_OPPOSITEZ = false;
  83657. _this.LODINREFLECTIONALPHA = false;
  83658. _this.GAMMAREFLECTION = false;
  83659. // Default BJS.
  83660. _this.MAINUV1 = false;
  83661. _this.MAINUV2 = false;
  83662. _this.UV1 = false;
  83663. _this.UV2 = false;
  83664. _this.CLIPPLANE = false;
  83665. _this.POINTSIZE = false;
  83666. _this.FOG = false;
  83667. _this.NORMAL = false;
  83668. _this.NUM_BONE_INFLUENCERS = 0;
  83669. _this.BonesPerMesh = 0;
  83670. _this.INSTANCES = false;
  83671. _this.SHADOWFLOAT = false;
  83672. _this.rebuild();
  83673. return _this;
  83674. }
  83675. return BackgroundMaterialDefines;
  83676. }(BABYLON.MaterialDefines));
  83677. /**
  83678. * Background material used to create an efficient environement around your scene.
  83679. */
  83680. var BackgroundMaterial = /** @class */ (function (_super) {
  83681. __extends(BackgroundMaterial, _super);
  83682. /**
  83683. * Instantiates a Background Material in the given scene
  83684. * @param name The friendly name of the material
  83685. * @param scene The scene to add the material to
  83686. */
  83687. function BackgroundMaterial(name, scene) {
  83688. var _this = _super.call(this, name, scene) || this;
  83689. /**
  83690. * Key light Color (multiply against the R channel of the environement texture)
  83691. */
  83692. _this.primaryColor = BABYLON.Color3.White();
  83693. /**
  83694. * Key light Level (allowing HDR output of the background)
  83695. */
  83696. _this.primaryLevel = 1;
  83697. /**
  83698. * Secondary light Color (multiply against the G channel of the environement texture)
  83699. */
  83700. _this.secondaryColor = BABYLON.Color3.Gray();
  83701. /**
  83702. * Secondary light Level (allowing HDR output of the background)
  83703. */
  83704. _this.secondaryLevel = 1;
  83705. /**
  83706. * Tertiary light Color (multiply against the B channel of the environement texture)
  83707. */
  83708. _this.tertiaryColor = BABYLON.Color3.Black();
  83709. /**
  83710. * Tertiary light Level (allowing HDR output of the background)
  83711. */
  83712. _this.tertiaryLevel = 1;
  83713. /**
  83714. * Reflection Texture used in the material.
  83715. * Should be author in a specific way for the best result (refer to the documentation).
  83716. */
  83717. _this.reflectionTexture = null;
  83718. /**
  83719. * Reflection Texture level of blur.
  83720. *
  83721. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  83722. * texture twice.
  83723. */
  83724. _this.reflectionBlur = 0;
  83725. /**
  83726. * Diffuse Texture used in the material.
  83727. * Should be author in a specific way for the best result (refer to the documentation).
  83728. */
  83729. _this.diffuseTexture = null;
  83730. _this._shadowLights = null;
  83731. /**
  83732. * Specify the list of lights casting shadow on the material.
  83733. * All scene shadow lights will be included if null.
  83734. */
  83735. _this.shadowLights = null;
  83736. /**
  83737. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  83738. * soft lighting on the background.
  83739. */
  83740. _this.shadowBlurScale = 1;
  83741. /**
  83742. * Helps adjusting the shadow to a softer level if required.
  83743. * 0 means black shadows and 1 means no shadows.
  83744. */
  83745. _this.shadowLevel = 0;
  83746. /**
  83747. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  83748. * It is usually zero but might be interesting to modify according to your setup.
  83749. */
  83750. _this.sceneCenter = BABYLON.Vector3.Zero();
  83751. /**
  83752. * This helps specifying that the material is falling off to the sky box at grazing angle.
  83753. * This helps ensuring a nice transition when the camera goes under the ground.
  83754. */
  83755. _this.opacityFresnel = true;
  83756. /**
  83757. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  83758. * This helps adding a mirror texture on the ground.
  83759. */
  83760. _this.reflectionFresnel = false;
  83761. /**
  83762. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  83763. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  83764. */
  83765. _this.reflectionFalloffDistance = 0.0;
  83766. /**
  83767. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  83768. */
  83769. _this.reflectionAmount = 1.0;
  83770. /**
  83771. * This specifies the weight of the reflection at grazing angle.
  83772. */
  83773. _this.reflectionReflectance0 = 0.05;
  83774. /**
  83775. * This specifies the weight of the reflection at a perpendicular point of view.
  83776. */
  83777. _this.reflectionReflectance90 = 0.5;
  83778. /**
  83779. * Helps to directly use the maps channels instead of their level.
  83780. */
  83781. _this.useRGBColor = true;
  83782. /**
  83783. * This helps reducing the banding effect that could occur on the background.
  83784. */
  83785. _this.enableNoise = false;
  83786. _this._maxSimultaneousLights = 4;
  83787. /**
  83788. * Number of Simultaneous lights allowed on the material.
  83789. */
  83790. _this.maxSimultaneousLights = 4;
  83791. /**
  83792. * Keep track of the image processing observer to allow dispose and replace.
  83793. */
  83794. _this._imageProcessingObserver = null;
  83795. // Temp values kept as cache in the material.
  83796. _this._renderTargets = new BABYLON.SmartArray(16);
  83797. _this._reflectionControls = BABYLON.Vector4.Zero();
  83798. // Setup the default processing configuration to the scene.
  83799. _this._attachImageProcessingConfiguration(null);
  83800. _this.getRenderTargetTextures = function () {
  83801. _this._renderTargets.reset();
  83802. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  83803. _this._renderTargets.push(_this._diffuseTexture);
  83804. }
  83805. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  83806. _this._renderTargets.push(_this._reflectionTexture);
  83807. }
  83808. return _this._renderTargets;
  83809. };
  83810. return _this;
  83811. }
  83812. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  83813. /**
  83814. * Sets the reflection reflectance fresnel values according to the default standard
  83815. * empirically know to work well :-)
  83816. */
  83817. set: function (value) {
  83818. var reflectionWeight = value;
  83819. if (reflectionWeight < 0.5) {
  83820. reflectionWeight = reflectionWeight * 2.0;
  83821. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  83822. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  83823. }
  83824. else {
  83825. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  83826. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  83827. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  83828. }
  83829. },
  83830. enumerable: true,
  83831. configurable: true
  83832. });
  83833. /**
  83834. * Attaches a new image processing configuration to the PBR Material.
  83835. * @param configuration (if null the scene configuration will be use)
  83836. */
  83837. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  83838. var _this = this;
  83839. if (configuration === this._imageProcessingConfiguration) {
  83840. return;
  83841. }
  83842. // Detaches observer.
  83843. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83844. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83845. }
  83846. // Pick the scene configuration if needed.
  83847. if (!configuration) {
  83848. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  83849. }
  83850. else {
  83851. this._imageProcessingConfiguration = configuration;
  83852. }
  83853. // Attaches observer.
  83854. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83855. _this._markAllSubMeshesAsImageProcessingDirty();
  83856. });
  83857. };
  83858. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  83859. /**
  83860. * Gets the image processing configuration used either in this material.
  83861. */
  83862. get: function () {
  83863. return this._imageProcessingConfiguration;
  83864. },
  83865. /**
  83866. * Sets the Default image processing configuration used either in the this material.
  83867. *
  83868. * If sets to null, the scene one is in use.
  83869. */
  83870. set: function (value) {
  83871. this._attachImageProcessingConfiguration(value);
  83872. // Ensure the effect will be rebuilt.
  83873. this._markAllSubMeshesAsTexturesDirty();
  83874. },
  83875. enumerable: true,
  83876. configurable: true
  83877. });
  83878. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  83879. /**
  83880. * Gets wether the color curves effect is enabled.
  83881. */
  83882. get: function () {
  83883. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83884. },
  83885. /**
  83886. * Sets wether the color curves effect is enabled.
  83887. */
  83888. set: function (value) {
  83889. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83890. },
  83891. enumerable: true,
  83892. configurable: true
  83893. });
  83894. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  83895. /**
  83896. * Gets wether the color grading effect is enabled.
  83897. */
  83898. get: function () {
  83899. return this.imageProcessingConfiguration.colorGradingEnabled;
  83900. },
  83901. /**
  83902. * Gets wether the color grading effect is enabled.
  83903. */
  83904. set: function (value) {
  83905. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83906. },
  83907. enumerable: true,
  83908. configurable: true
  83909. });
  83910. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  83911. /**
  83912. * Gets wether tonemapping is enabled or not.
  83913. */
  83914. get: function () {
  83915. return this._imageProcessingConfiguration.toneMappingEnabled;
  83916. },
  83917. /**
  83918. * Sets wether tonemapping is enabled or not
  83919. */
  83920. set: function (value) {
  83921. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83922. },
  83923. enumerable: true,
  83924. configurable: true
  83925. });
  83926. ;
  83927. ;
  83928. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  83929. /**
  83930. * The camera exposure used on this material.
  83931. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83932. * This corresponds to a photographic exposure.
  83933. */
  83934. get: function () {
  83935. return this._imageProcessingConfiguration.exposure;
  83936. },
  83937. /**
  83938. * The camera exposure used on this material.
  83939. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83940. * This corresponds to a photographic exposure.
  83941. */
  83942. set: function (value) {
  83943. this._imageProcessingConfiguration.exposure = value;
  83944. },
  83945. enumerable: true,
  83946. configurable: true
  83947. });
  83948. ;
  83949. ;
  83950. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  83951. /**
  83952. * Gets The camera contrast used on this material.
  83953. */
  83954. get: function () {
  83955. return this._imageProcessingConfiguration.contrast;
  83956. },
  83957. /**
  83958. * Sets The camera contrast used on this material.
  83959. */
  83960. set: function (value) {
  83961. this._imageProcessingConfiguration.contrast = value;
  83962. },
  83963. enumerable: true,
  83964. configurable: true
  83965. });
  83966. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  83967. /**
  83968. * Gets the Color Grading 2D Lookup Texture.
  83969. */
  83970. get: function () {
  83971. return this._imageProcessingConfiguration.colorGradingTexture;
  83972. },
  83973. /**
  83974. * Sets the Color Grading 2D Lookup Texture.
  83975. */
  83976. set: function (value) {
  83977. this.imageProcessingConfiguration.colorGradingTexture = value;
  83978. },
  83979. enumerable: true,
  83980. configurable: true
  83981. });
  83982. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  83983. /**
  83984. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83985. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83986. * 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;
  83987. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83988. */
  83989. get: function () {
  83990. return this.imageProcessingConfiguration.colorCurves;
  83991. },
  83992. /**
  83993. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83994. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83995. * 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;
  83996. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83997. */
  83998. set: function (value) {
  83999. this.imageProcessingConfiguration.colorCurves = value;
  84000. },
  84001. enumerable: true,
  84002. configurable: true
  84003. });
  84004. /**
  84005. * The entire material has been created in order to prevent overdraw.
  84006. * @returns false
  84007. */
  84008. BackgroundMaterial.prototype.needAlphaTesting = function () {
  84009. return true;
  84010. };
  84011. /**
  84012. * The entire material has been created in order to prevent overdraw.
  84013. * @returns true if blending is enable
  84014. */
  84015. BackgroundMaterial.prototype.needAlphaBlending = function () {
  84016. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  84017. };
  84018. /**
  84019. * Checks wether the material is ready to be rendered for a given mesh.
  84020. * @param mesh The mesh to render
  84021. * @param subMesh The submesh to check against
  84022. * @param useInstances Specify wether or not the material is used with instances
  84023. * @returns true if all the dependencies are ready (Textures, Effects...)
  84024. */
  84025. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  84026. var _this = this;
  84027. if (useInstances === void 0) { useInstances = false; }
  84028. if (subMesh.effect && this.isFrozen) {
  84029. if (this._wasPreviouslyReady) {
  84030. return true;
  84031. }
  84032. }
  84033. if (!subMesh._materialDefines) {
  84034. subMesh._materialDefines = new BackgroundMaterialDefines();
  84035. }
  84036. var scene = this.getScene();
  84037. var defines = subMesh._materialDefines;
  84038. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  84039. if (defines._renderId === scene.getRenderId()) {
  84040. return true;
  84041. }
  84042. }
  84043. var engine = scene.getEngine();
  84044. // Lights
  84045. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  84046. defines._needNormals = true;
  84047. // Textures
  84048. if (defines._areTexturesDirty) {
  84049. defines._needUVs = false;
  84050. if (scene.texturesEnabled) {
  84051. if (scene.getEngine().getCaps().textureLOD) {
  84052. defines.TEXTURELODSUPPORT = true;
  84053. }
  84054. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84055. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  84056. return false;
  84057. }
  84058. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  84059. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  84060. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  84061. defines.OPACITYFRESNEL = this._opacityFresnel;
  84062. }
  84063. else {
  84064. defines.DIFFUSE = false;
  84065. defines.DIFFUSEHASALPHA = false;
  84066. defines.GAMMADIFFUSE = false;
  84067. defines.OPACITYFRESNEL = false;
  84068. }
  84069. var reflectionTexture = this._reflectionTexture;
  84070. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84071. if (!reflectionTexture.isReadyOrNotBlocking()) {
  84072. return false;
  84073. }
  84074. defines.REFLECTION = true;
  84075. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  84076. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  84077. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  84078. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  84079. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  84080. defines.INVERTCUBICMAP = true;
  84081. }
  84082. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  84083. switch (reflectionTexture.coordinatesMode) {
  84084. case BABYLON.Texture.CUBIC_MODE:
  84085. case BABYLON.Texture.INVCUBIC_MODE:
  84086. defines.REFLECTIONMAP_CUBIC = true;
  84087. break;
  84088. case BABYLON.Texture.EXPLICIT_MODE:
  84089. defines.REFLECTIONMAP_EXPLICIT = true;
  84090. break;
  84091. case BABYLON.Texture.PLANAR_MODE:
  84092. defines.REFLECTIONMAP_PLANAR = true;
  84093. break;
  84094. case BABYLON.Texture.PROJECTION_MODE:
  84095. defines.REFLECTIONMAP_PROJECTION = true;
  84096. break;
  84097. case BABYLON.Texture.SKYBOX_MODE:
  84098. defines.REFLECTIONMAP_SKYBOX = true;
  84099. break;
  84100. case BABYLON.Texture.SPHERICAL_MODE:
  84101. defines.REFLECTIONMAP_SPHERICAL = true;
  84102. break;
  84103. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  84104. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  84105. break;
  84106. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  84107. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  84108. break;
  84109. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  84110. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  84111. break;
  84112. }
  84113. if (this.reflectionFresnel) {
  84114. defines.REFLECTIONFRESNEL = true;
  84115. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  84116. this._reflectionControls.x = this.reflectionAmount;
  84117. this._reflectionControls.y = this.reflectionReflectance0;
  84118. this._reflectionControls.z = this.reflectionReflectance90;
  84119. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  84120. }
  84121. else {
  84122. defines.REFLECTIONFRESNEL = false;
  84123. defines.REFLECTIONFALLOFF = false;
  84124. }
  84125. }
  84126. else {
  84127. defines.REFLECTION = false;
  84128. defines.REFLECTIONFALLOFF = false;
  84129. defines.REFLECTIONBLUR = false;
  84130. defines.REFLECTIONMAP_3D = false;
  84131. defines.REFLECTIONMAP_SPHERICAL = false;
  84132. defines.REFLECTIONMAP_PLANAR = false;
  84133. defines.REFLECTIONMAP_CUBIC = false;
  84134. defines.REFLECTIONMAP_PROJECTION = false;
  84135. defines.REFLECTIONMAP_SKYBOX = false;
  84136. defines.REFLECTIONMAP_EXPLICIT = false;
  84137. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84138. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84139. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84140. defines.INVERTCUBICMAP = false;
  84141. defines.REFLECTIONMAP_OPPOSITEZ = false;
  84142. defines.LODINREFLECTIONALPHA = false;
  84143. defines.GAMMAREFLECTION = false;
  84144. }
  84145. }
  84146. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  84147. defines.USERGBCOLOR = this._useRGBColor;
  84148. defines.NOISE = this._enableNoise;
  84149. }
  84150. if (defines._areImageProcessingDirty) {
  84151. if (!this._imageProcessingConfiguration.isReady()) {
  84152. return false;
  84153. }
  84154. this._imageProcessingConfiguration.prepareDefines(defines);
  84155. }
  84156. // Misc.
  84157. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  84158. // Values that need to be evaluated on every frame
  84159. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  84160. // Attribs
  84161. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  84162. if (mesh) {
  84163. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84164. mesh.createNormals(true);
  84165. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  84166. }
  84167. }
  84168. }
  84169. // Get correct effect
  84170. if (defines.isDirty) {
  84171. defines.markAsProcessed();
  84172. scene.resetCachedMaterial();
  84173. // Fallbacks
  84174. var fallbacks = new BABYLON.EffectFallbacks();
  84175. if (defines.FOG) {
  84176. fallbacks.addFallback(0, "FOG");
  84177. }
  84178. if (defines.POINTSIZE) {
  84179. fallbacks.addFallback(1, "POINTSIZE");
  84180. }
  84181. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  84182. if (defines.NUM_BONE_INFLUENCERS > 0) {
  84183. fallbacks.addCPUSkinningFallback(0, mesh);
  84184. }
  84185. //Attributes
  84186. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84187. if (defines.NORMAL) {
  84188. attribs.push(BABYLON.VertexBuffer.NormalKind);
  84189. }
  84190. if (defines.UV1) {
  84191. attribs.push(BABYLON.VertexBuffer.UVKind);
  84192. }
  84193. if (defines.UV2) {
  84194. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84195. }
  84196. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  84197. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  84198. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  84199. "vFogInfos", "vFogColor", "pointSize",
  84200. "vClipPlane", "mBones",
  84201. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  84202. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  84203. "shadowLevel", "alpha",
  84204. "vBackgroundCenter", "vReflectionControl",
  84205. "vDiffuseInfos", "diffuseMatrix",
  84206. ];
  84207. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  84208. var uniformBuffers = ["Material", "Scene"];
  84209. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  84210. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  84211. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  84212. uniformsNames: uniforms,
  84213. uniformBuffersNames: uniformBuffers,
  84214. samplers: samplers,
  84215. defines: defines,
  84216. maxSimultaneousLights: this._maxSimultaneousLights
  84217. });
  84218. var onCompiled = function (effect) {
  84219. if (_this.onCompiled) {
  84220. _this.onCompiled(effect);
  84221. }
  84222. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  84223. };
  84224. var join = defines.toString();
  84225. subMesh.setEffect(scene.getEngine().createEffect("background", {
  84226. attributes: attribs,
  84227. uniformsNames: uniforms,
  84228. uniformBuffersNames: uniformBuffers,
  84229. samplers: samplers,
  84230. defines: join,
  84231. fallbacks: fallbacks,
  84232. onCompiled: onCompiled,
  84233. onError: this.onError,
  84234. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  84235. }, engine), defines);
  84236. this.buildUniformLayout();
  84237. }
  84238. if (!subMesh.effect || !subMesh.effect.isReady()) {
  84239. return false;
  84240. }
  84241. defines._renderId = scene.getRenderId();
  84242. this._wasPreviouslyReady = true;
  84243. return true;
  84244. };
  84245. /**
  84246. * Build the uniform buffer used in the material.
  84247. */
  84248. BackgroundMaterial.prototype.buildUniformLayout = function () {
  84249. // Order is important !
  84250. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  84251. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  84252. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  84253. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  84254. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  84255. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  84256. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  84257. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  84258. this._uniformBuffer.addUniform("pointSize", 1);
  84259. this._uniformBuffer.addUniform("shadowLevel", 1);
  84260. this._uniformBuffer.addUniform("alpha", 1);
  84261. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  84262. this._uniformBuffer.addUniform("vReflectionControl", 4);
  84263. this._uniformBuffer.create();
  84264. };
  84265. /**
  84266. * Unbind the material.
  84267. */
  84268. BackgroundMaterial.prototype.unbind = function () {
  84269. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  84270. this._uniformBuffer.setTexture("diffuseSampler", null);
  84271. }
  84272. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  84273. this._uniformBuffer.setTexture("reflectionSampler", null);
  84274. }
  84275. _super.prototype.unbind.call(this);
  84276. };
  84277. /**
  84278. * Bind only the world matrix to the material.
  84279. * @param world The world matrix to bind.
  84280. */
  84281. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  84282. this._activeEffect.setMatrix("world", world);
  84283. };
  84284. /**
  84285. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  84286. * @param world The world matrix to bind.
  84287. * @param subMesh The submesh to bind for.
  84288. */
  84289. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  84290. var scene = this.getScene();
  84291. var defines = subMesh._materialDefines;
  84292. if (!defines) {
  84293. return;
  84294. }
  84295. var effect = subMesh.effect;
  84296. if (!effect) {
  84297. return;
  84298. }
  84299. this._activeEffect = effect;
  84300. // Matrices
  84301. this.bindOnlyWorldMatrix(world);
  84302. // Bones
  84303. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  84304. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  84305. if (mustRebind) {
  84306. this._uniformBuffer.bindToEffect(effect, "Material");
  84307. this.bindViewProjection(effect);
  84308. var reflectionTexture = this._reflectionTexture;
  84309. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  84310. // Texture uniforms
  84311. if (scene.texturesEnabled) {
  84312. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84313. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  84314. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  84315. }
  84316. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84317. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  84318. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  84319. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  84320. }
  84321. }
  84322. if (this.shadowLevel > 0) {
  84323. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  84324. }
  84325. this._uniformBuffer.updateFloat("alpha", this.alpha);
  84326. // Point size
  84327. if (this.pointsCloud) {
  84328. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  84329. }
  84330. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  84331. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  84332. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  84333. }
  84334. // Textures
  84335. if (scene.texturesEnabled) {
  84336. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84337. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  84338. }
  84339. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84340. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  84341. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84342. }
  84343. else if (!defines.REFLECTIONBLUR) {
  84344. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84345. }
  84346. else {
  84347. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  84348. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  84349. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  84350. }
  84351. if (defines.REFLECTIONFRESNEL) {
  84352. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  84353. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  84354. }
  84355. }
  84356. }
  84357. // Clip plane
  84358. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  84359. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  84360. }
  84361. if (mustRebind || !this.isFrozen) {
  84362. if (scene.lightsEnabled) {
  84363. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  84364. }
  84365. // View
  84366. this.bindView(effect);
  84367. // Fog
  84368. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84369. // image processing
  84370. this._imageProcessingConfiguration.bind(this._activeEffect);
  84371. }
  84372. this._uniformBuffer.update();
  84373. this._afterBind(mesh);
  84374. };
  84375. /**
  84376. * Dispose the material.
  84377. * @param forceDisposeEffect Force disposal of the associated effect.
  84378. * @param forceDisposeTextures Force disposal of the associated textures.
  84379. */
  84380. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  84381. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  84382. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  84383. if (forceDisposeTextures) {
  84384. if (this.diffuseTexture) {
  84385. this.diffuseTexture.dispose();
  84386. }
  84387. if (this.reflectionTexture) {
  84388. this.reflectionTexture.dispose();
  84389. }
  84390. }
  84391. this._renderTargets.dispose();
  84392. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84393. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84394. }
  84395. _super.prototype.dispose.call(this, forceDisposeEffect);
  84396. };
  84397. /**
  84398. * Clones the material.
  84399. * @param name The cloned name.
  84400. * @returns The cloned material.
  84401. */
  84402. BackgroundMaterial.prototype.clone = function (name) {
  84403. var _this = this;
  84404. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  84405. };
  84406. /**
  84407. * Serializes the current material to its JSON representation.
  84408. * @returns The JSON representation.
  84409. */
  84410. BackgroundMaterial.prototype.serialize = function () {
  84411. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84412. serializationObject.customType = "BABYLON.BackgroundMaterial";
  84413. return serializationObject;
  84414. };
  84415. /**
  84416. * Gets the class name of the material
  84417. * @returns "BackgroundMaterial"
  84418. */
  84419. BackgroundMaterial.prototype.getClassName = function () {
  84420. return "BackgroundMaterial";
  84421. };
  84422. /**
  84423. * Parse a JSON input to create back a background material.
  84424. * @param source The JSON data to parse
  84425. * @param scene The scene to create the parsed material in
  84426. * @param rootUrl The root url of the assets the material depends upon
  84427. * @returns the instantiated BackgroundMaterial.
  84428. */
  84429. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  84430. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  84431. };
  84432. /**
  84433. * Standard reflectance value at parallel view angle.
  84434. */
  84435. BackgroundMaterial.StandardReflectance0 = 0.05;
  84436. /**
  84437. * Standard reflectance value at grazing angle.
  84438. */
  84439. BackgroundMaterial.StandardReflectance90 = 0.5;
  84440. __decorate([
  84441. BABYLON.serializeAsColor3()
  84442. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  84443. __decorate([
  84444. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84445. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  84446. __decorate([
  84447. BABYLON.serialize()
  84448. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  84449. __decorate([
  84450. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84451. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  84452. __decorate([
  84453. BABYLON.serializeAsColor3()
  84454. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  84455. __decorate([
  84456. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84457. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  84458. __decorate([
  84459. BABYLON.serialize()
  84460. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  84461. __decorate([
  84462. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84463. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  84464. __decorate([
  84465. BABYLON.serializeAsColor3()
  84466. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  84467. __decorate([
  84468. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84469. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  84470. __decorate([
  84471. BABYLON.serialize()
  84472. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  84473. __decorate([
  84474. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84475. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  84476. __decorate([
  84477. BABYLON.serializeAsTexture()
  84478. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  84479. __decorate([
  84480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84481. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  84482. __decorate([
  84483. BABYLON.serialize()
  84484. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  84485. __decorate([
  84486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84487. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  84488. __decorate([
  84489. BABYLON.serializeAsTexture()
  84490. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  84491. __decorate([
  84492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84493. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  84494. __decorate([
  84495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84496. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  84497. __decorate([
  84498. BABYLON.serialize()
  84499. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  84500. __decorate([
  84501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84502. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  84503. __decorate([
  84504. BABYLON.serialize()
  84505. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  84506. __decorate([
  84507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84508. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  84509. __decorate([
  84510. BABYLON.serializeAsVector3()
  84511. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  84512. __decorate([
  84513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84514. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  84515. __decorate([
  84516. BABYLON.serialize()
  84517. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  84518. __decorate([
  84519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84520. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  84521. __decorate([
  84522. BABYLON.serialize()
  84523. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  84524. __decorate([
  84525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84526. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  84527. __decorate([
  84528. BABYLON.serialize()
  84529. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  84530. __decorate([
  84531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84532. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  84533. __decorate([
  84534. BABYLON.serialize()
  84535. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  84536. __decorate([
  84537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84538. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  84539. __decorate([
  84540. BABYLON.serialize()
  84541. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  84542. __decorate([
  84543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84544. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  84545. __decorate([
  84546. BABYLON.serialize()
  84547. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  84548. __decorate([
  84549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84550. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  84551. __decorate([
  84552. BABYLON.serialize()
  84553. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  84554. __decorate([
  84555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84556. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  84557. __decorate([
  84558. BABYLON.serialize()
  84559. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  84560. __decorate([
  84561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84562. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  84563. __decorate([
  84564. BABYLON.serialize()
  84565. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  84566. __decorate([
  84567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84568. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  84569. __decorate([
  84570. BABYLON.serializeAsImageProcessingConfiguration()
  84571. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  84572. return BackgroundMaterial;
  84573. }(BABYLON.PushMaterial));
  84574. BABYLON.BackgroundMaterial = BackgroundMaterial;
  84575. })(BABYLON || (BABYLON = {}));
  84576. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  84577. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84578. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84579. s = arguments[i];
  84580. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84581. t[p] = s[p];
  84582. }
  84583. return t;
  84584. };
  84585. var BABYLON;
  84586. (function (BABYLON) {
  84587. /**
  84588. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  84589. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  84590. * It also helps with the default setup of your imageProcessing configuration.
  84591. */
  84592. var EnvironmentHelper = /** @class */ (function () {
  84593. /**
  84594. * constructor
  84595. * @param options
  84596. * @param scene The scene to add the material to
  84597. */
  84598. function EnvironmentHelper(options, scene) {
  84599. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  84600. this._scene = scene;
  84601. this._setupBackground();
  84602. this._setupImageProcessing();
  84603. }
  84604. /**
  84605. * Creates the default options for the helper.
  84606. */
  84607. EnvironmentHelper._getDefaultOptions = function () {
  84608. return {
  84609. createGround: true,
  84610. groundSize: 15,
  84611. groundTexture: this._groundTextureCDNUrl,
  84612. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84613. groundOpacity: 0.9,
  84614. enableGroundShadow: true,
  84615. groundShadowLevel: 0.5,
  84616. enableGroundMirror: false,
  84617. groundMirrorSizeRatio: 0.3,
  84618. groundMirrorBlurKernel: 64,
  84619. groundMirrorAmount: 1,
  84620. groundMirrorFresnelWeight: 1,
  84621. groundMirrorFallOffDistance: 0,
  84622. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  84623. groundYBias: 0.00001,
  84624. createSkybox: true,
  84625. skyboxSize: 20,
  84626. skyboxTexture: this._skyboxTextureCDNUrl,
  84627. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84628. backgroundYRotation: 0,
  84629. sizeAuto: true,
  84630. rootPosition: BABYLON.Vector3.Zero(),
  84631. setupImageProcessing: true,
  84632. environmentTexture: this._environmentTextureCDNUrl,
  84633. cameraExposure: 0.8,
  84634. cameraContrast: 1.2,
  84635. toneMappingEnabled: true,
  84636. };
  84637. };
  84638. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  84639. /**
  84640. * Gets the root mesh created by the helper.
  84641. */
  84642. get: function () {
  84643. return this._rootMesh;
  84644. },
  84645. enumerable: true,
  84646. configurable: true
  84647. });
  84648. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  84649. /**
  84650. * Gets the skybox created by the helper.
  84651. */
  84652. get: function () {
  84653. return this._skybox;
  84654. },
  84655. enumerable: true,
  84656. configurable: true
  84657. });
  84658. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  84659. /**
  84660. * Gets the skybox texture created by the helper.
  84661. */
  84662. get: function () {
  84663. return this._skyboxTexture;
  84664. },
  84665. enumerable: true,
  84666. configurable: true
  84667. });
  84668. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  84669. /**
  84670. * Gets the skybox material created by the helper.
  84671. */
  84672. get: function () {
  84673. return this._skyboxMaterial;
  84674. },
  84675. enumerable: true,
  84676. configurable: true
  84677. });
  84678. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  84679. /**
  84680. * Gets the ground mesh created by the helper.
  84681. */
  84682. get: function () {
  84683. return this._ground;
  84684. },
  84685. enumerable: true,
  84686. configurable: true
  84687. });
  84688. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  84689. /**
  84690. * Gets the ground texture created by the helper.
  84691. */
  84692. get: function () {
  84693. return this._groundTexture;
  84694. },
  84695. enumerable: true,
  84696. configurable: true
  84697. });
  84698. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  84699. /**
  84700. * Gets the ground mirror created by the helper.
  84701. */
  84702. get: function () {
  84703. return this._groundMirror;
  84704. },
  84705. enumerable: true,
  84706. configurable: true
  84707. });
  84708. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  84709. /**
  84710. * Gets the ground mirror render list to helps pushing the meshes
  84711. * you wish in the ground reflection.
  84712. */
  84713. get: function () {
  84714. if (this._groundMirror) {
  84715. return this._groundMirror.renderList;
  84716. }
  84717. return null;
  84718. },
  84719. enumerable: true,
  84720. configurable: true
  84721. });
  84722. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  84723. /**
  84724. * Gets the ground material created by the helper.
  84725. */
  84726. get: function () {
  84727. return this._groundMaterial;
  84728. },
  84729. enumerable: true,
  84730. configurable: true
  84731. });
  84732. /**
  84733. * Updates the background according to the new options
  84734. * @param options
  84735. */
  84736. EnvironmentHelper.prototype.updateOptions = function (options) {
  84737. var newOptions = __assign({}, this._options, options);
  84738. if (this._ground && !newOptions.createGround) {
  84739. this._ground.dispose();
  84740. this._ground = null;
  84741. }
  84742. if (this._groundMaterial && !newOptions.createGround) {
  84743. this._groundMaterial.dispose();
  84744. this._groundMaterial = null;
  84745. }
  84746. if (this._groundTexture) {
  84747. if (this._options.groundTexture != newOptions.groundTexture) {
  84748. this._groundTexture.dispose();
  84749. this._groundTexture = null;
  84750. }
  84751. }
  84752. if (this._skybox && !newOptions.createSkybox) {
  84753. this._skybox.dispose();
  84754. this._skybox = null;
  84755. }
  84756. if (this._skyboxMaterial && !newOptions.createSkybox) {
  84757. this._skyboxMaterial.dispose();
  84758. this._skyboxMaterial = null;
  84759. }
  84760. if (this._skyboxTexture) {
  84761. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  84762. this._skyboxTexture.dispose();
  84763. this._skyboxTexture = null;
  84764. }
  84765. }
  84766. if (this._groundMirror && !newOptions.enableGroundMirror) {
  84767. this._groundMirror.dispose();
  84768. this._groundMirror = null;
  84769. }
  84770. if (this._scene.environmentTexture) {
  84771. if (this._options.environmentTexture != newOptions.environmentTexture) {
  84772. this._scene.environmentTexture.dispose();
  84773. }
  84774. }
  84775. this._options = newOptions;
  84776. this._setupBackground();
  84777. this._setupImageProcessing();
  84778. };
  84779. /**
  84780. * Sets the primary color of all the available elements.
  84781. * @param color
  84782. */
  84783. EnvironmentHelper.prototype.setMainColor = function (color) {
  84784. if (this.groundMaterial) {
  84785. this.groundMaterial.primaryColor = color;
  84786. }
  84787. if (this.skyboxMaterial) {
  84788. this.skyboxMaterial.primaryColor = color;
  84789. }
  84790. if (this.groundMirror) {
  84791. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  84792. }
  84793. };
  84794. /**
  84795. * Setup the image processing according to the specified options.
  84796. */
  84797. EnvironmentHelper.prototype._setupImageProcessing = function () {
  84798. if (this._options.setupImageProcessing) {
  84799. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  84800. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  84801. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  84802. this._setupEnvironmentTexture();
  84803. }
  84804. };
  84805. /**
  84806. * Setup the environment texture according to the specified options.
  84807. */
  84808. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  84809. if (this._scene.environmentTexture) {
  84810. return;
  84811. }
  84812. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  84813. this._scene.environmentTexture = this._options.environmentTexture;
  84814. return;
  84815. }
  84816. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  84817. this._scene.environmentTexture = environmentTexture;
  84818. };
  84819. /**
  84820. * Setup the background according to the specified options.
  84821. */
  84822. EnvironmentHelper.prototype._setupBackground = function () {
  84823. if (!this._rootMesh) {
  84824. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  84825. }
  84826. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  84827. var sceneSize = this._getSceneSize();
  84828. if (this._options.createGround) {
  84829. this._setupGround(sceneSize);
  84830. this._setupGroundMaterial();
  84831. this._setupGroundDiffuseTexture();
  84832. if (this._options.enableGroundMirror) {
  84833. this._setupGroundMirrorTexture(sceneSize);
  84834. }
  84835. this._setupMirrorInGroundMaterial();
  84836. }
  84837. if (this._options.createSkybox) {
  84838. this._setupSkybox(sceneSize);
  84839. this._setupSkyboxMaterial();
  84840. this._setupSkyboxReflectionTexture();
  84841. }
  84842. this._rootMesh.position.x = sceneSize.rootPosition.x;
  84843. this._rootMesh.position.z = sceneSize.rootPosition.z;
  84844. this._rootMesh.position.y = sceneSize.rootPosition.y;
  84845. };
  84846. /**
  84847. * Get the scene sizes according to the setup.
  84848. */
  84849. EnvironmentHelper.prototype._getSceneSize = function () {
  84850. var groundSize = this._options.groundSize;
  84851. var skyboxSize = this._options.skyboxSize;
  84852. var rootPosition = this._options.rootPosition;
  84853. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  84854. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84855. }
  84856. var sceneExtends = this._scene.getWorldExtends();
  84857. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  84858. if (this._options.sizeAuto) {
  84859. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  84860. this._scene.activeCamera.upperRadiusLimit) {
  84861. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  84862. skyboxSize = groundSize;
  84863. }
  84864. var sceneDiagonalLenght = sceneDiagonal.length();
  84865. if (sceneDiagonalLenght > groundSize) {
  84866. groundSize = sceneDiagonalLenght * 2;
  84867. skyboxSize = groundSize;
  84868. }
  84869. // 10 % bigger.
  84870. groundSize *= 1.1;
  84871. skyboxSize *= 1.5;
  84872. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  84873. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  84874. }
  84875. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84876. };
  84877. /**
  84878. * Setup the ground according to the specified options.
  84879. */
  84880. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  84881. var _this = this;
  84882. if (!this._ground) {
  84883. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  84884. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  84885. this._ground.parent = this._rootMesh;
  84886. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  84887. }
  84888. this._ground.receiveShadows = this._options.enableGroundShadow;
  84889. };
  84890. /**
  84891. * Setup the ground material according to the specified options.
  84892. */
  84893. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  84894. if (!this._groundMaterial) {
  84895. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  84896. }
  84897. this._groundMaterial.alpha = this._options.groundOpacity;
  84898. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  84899. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  84900. this._groundMaterial.primaryLevel = 1;
  84901. this._groundMaterial.primaryColor = this._options.groundColor;
  84902. this._groundMaterial.secondaryLevel = 0;
  84903. this._groundMaterial.tertiaryLevel = 0;
  84904. this._groundMaterial.useRGBColor = false;
  84905. this._groundMaterial.enableNoise = true;
  84906. if (this._ground) {
  84907. this._ground.material = this._groundMaterial;
  84908. }
  84909. };
  84910. /**
  84911. * Setup the ground diffuse texture according to the specified options.
  84912. */
  84913. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  84914. if (!this._groundMaterial) {
  84915. return;
  84916. }
  84917. if (this._groundTexture) {
  84918. return;
  84919. }
  84920. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  84921. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  84922. return;
  84923. }
  84924. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  84925. diffuseTexture.gammaSpace = false;
  84926. diffuseTexture.hasAlpha = true;
  84927. this._groundMaterial.diffuseTexture = diffuseTexture;
  84928. };
  84929. /**
  84930. * Setup the ground mirror texture according to the specified options.
  84931. */
  84932. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  84933. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84934. if (!this._groundMirror) {
  84935. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  84936. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  84937. this._groundMirror.anisotropicFilteringLevel = 1;
  84938. this._groundMirror.wrapU = wrapping;
  84939. this._groundMirror.wrapV = wrapping;
  84940. this._groundMirror.gammaSpace = false;
  84941. if (this._groundMirror.renderList) {
  84942. for (var i = 0; i < this._scene.meshes.length; i++) {
  84943. var mesh = this._scene.meshes[i];
  84944. if (mesh !== this._ground &&
  84945. mesh !== this._skybox &&
  84946. mesh !== this._rootMesh) {
  84947. this._groundMirror.renderList.push(mesh);
  84948. }
  84949. }
  84950. }
  84951. }
  84952. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  84953. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  84954. };
  84955. /**
  84956. * Setup the ground to receive the mirror texture.
  84957. */
  84958. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  84959. if (this._groundMaterial) {
  84960. this._groundMaterial.reflectionTexture = this._groundMirror;
  84961. this._groundMaterial.reflectionFresnel = true;
  84962. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  84963. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  84964. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  84965. }
  84966. };
  84967. /**
  84968. * Setup the skybox according to the specified options.
  84969. */
  84970. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  84971. var _this = this;
  84972. if (!this._skybox) {
  84973. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  84974. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  84975. }
  84976. this._skybox.parent = this._rootMesh;
  84977. };
  84978. /**
  84979. * Setup the skybox material according to the specified options.
  84980. */
  84981. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  84982. if (!this._skybox) {
  84983. return;
  84984. }
  84985. if (!this._skyboxMaterial) {
  84986. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  84987. }
  84988. this._skyboxMaterial.useRGBColor = false;
  84989. this._skyboxMaterial.primaryLevel = 1;
  84990. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  84991. this._skyboxMaterial.secondaryLevel = 0;
  84992. this._skyboxMaterial.tertiaryLevel = 0;
  84993. this._skyboxMaterial.enableNoise = true;
  84994. this._skybox.material = this._skyboxMaterial;
  84995. };
  84996. /**
  84997. * Setup the skybox reflection texture according to the specified options.
  84998. */
  84999. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  85000. if (!this._skyboxMaterial) {
  85001. return;
  85002. }
  85003. if (this._skyboxTexture) {
  85004. return;
  85005. }
  85006. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  85007. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85008. return;
  85009. }
  85010. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  85011. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  85012. this._skyboxTexture.gammaSpace = false;
  85013. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85014. };
  85015. /**
  85016. * Dispose all the elements created by the Helper.
  85017. */
  85018. EnvironmentHelper.prototype.dispose = function () {
  85019. if (this._groundMaterial) {
  85020. this._groundMaterial.dispose(true, true);
  85021. }
  85022. if (this._skyboxMaterial) {
  85023. this._skyboxMaterial.dispose(true, true);
  85024. }
  85025. this._rootMesh.dispose(false);
  85026. };
  85027. /**
  85028. * Default ground texture URL.
  85029. */
  85030. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  85031. /**
  85032. * Default skybox texture URL.
  85033. */
  85034. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  85035. /**
  85036. * Default environment texture URL.
  85037. */
  85038. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  85039. return EnvironmentHelper;
  85040. }());
  85041. BABYLON.EnvironmentHelper = EnvironmentHelper;
  85042. })(BABYLON || (BABYLON = {}));
  85043. //# sourceMappingURL=babylon.environmentHelper.js.map
  85044. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  85045. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nlightingInfo computeProjectionTexture(lightingInfo origin,sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nlightingInfo result=origin;\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec4 textureColor=texture2D(projectionLightSampler,strq.xy);\nresult.diffuse*=vec3(textureColor);\nreturn result;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo=computeProjectionTexture(info,projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  85046. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85047. var BABYLON;
  85048. (function (BABYLON) {
  85049. var GridMaterialDefines = /** @class */ (function (_super) {
  85050. __extends(GridMaterialDefines, _super);
  85051. function GridMaterialDefines() {
  85052. var _this = _super.call(this) || this;
  85053. _this.TRANSPARENT = false;
  85054. _this.FOG = false;
  85055. _this.PREMULTIPLYALPHA = false;
  85056. _this.rebuild();
  85057. return _this;
  85058. }
  85059. return GridMaterialDefines;
  85060. }(BABYLON.MaterialDefines));
  85061. /**
  85062. * The grid materials allows you to wrap any shape with a grid.
  85063. * Colors are customizable.
  85064. */
  85065. var GridMaterial = /** @class */ (function (_super) {
  85066. __extends(GridMaterial, _super);
  85067. /**
  85068. * constructor
  85069. * @param name The name given to the material in order to identify it afterwards.
  85070. * @param scene The scene the material is used in.
  85071. */
  85072. function GridMaterial(name, scene) {
  85073. var _this = _super.call(this, name, scene) || this;
  85074. /**
  85075. * Main color of the grid (e.g. between lines)
  85076. */
  85077. _this.mainColor = BABYLON.Color3.Black();
  85078. /**
  85079. * Color of the grid lines.
  85080. */
  85081. _this.lineColor = BABYLON.Color3.Teal();
  85082. /**
  85083. * The scale of the grid compared to unit.
  85084. */
  85085. _this.gridRatio = 1.0;
  85086. /**
  85087. * Allows setting an offset for the grid lines.
  85088. */
  85089. _this.gridOffset = BABYLON.Vector3.Zero();
  85090. /**
  85091. * The frequency of thicker lines.
  85092. */
  85093. _this.majorUnitFrequency = 10;
  85094. /**
  85095. * The visibility of minor units in the grid.
  85096. */
  85097. _this.minorUnitVisibility = 0.33;
  85098. /**
  85099. * The grid opacity outside of the lines.
  85100. */
  85101. _this.opacity = 1.0;
  85102. /**
  85103. * Determine RBG output is premultiplied by alpha value.
  85104. */
  85105. _this.preMultiplyAlpha = false;
  85106. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  85107. return _this;
  85108. }
  85109. /**
  85110. * Returns wehter or not the grid requires alpha blending.
  85111. */
  85112. GridMaterial.prototype.needAlphaBlending = function () {
  85113. return this.opacity < 1.0;
  85114. };
  85115. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  85116. return this.needAlphaBlending();
  85117. };
  85118. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85119. if (this.isFrozen) {
  85120. if (this._wasPreviouslyReady && subMesh.effect) {
  85121. return true;
  85122. }
  85123. }
  85124. if (!subMesh._materialDefines) {
  85125. subMesh._materialDefines = new GridMaterialDefines();
  85126. }
  85127. var defines = subMesh._materialDefines;
  85128. var scene = this.getScene();
  85129. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85130. if (this._renderId === scene.getRenderId()) {
  85131. return true;
  85132. }
  85133. }
  85134. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  85135. defines.TRANSPARENT = !defines.TRANSPARENT;
  85136. defines.markAsUnprocessed();
  85137. }
  85138. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  85139. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  85140. defines.markAsUnprocessed();
  85141. }
  85142. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  85143. // Get correct effect
  85144. if (defines.isDirty) {
  85145. defines.markAsProcessed();
  85146. scene.resetCachedMaterial();
  85147. // Attributes
  85148. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85149. // Defines
  85150. var join = defines.toString();
  85151. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  85152. }
  85153. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85154. return false;
  85155. }
  85156. this._renderId = scene.getRenderId();
  85157. this._wasPreviouslyReady = true;
  85158. return true;
  85159. };
  85160. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85161. var scene = this.getScene();
  85162. var defines = subMesh._materialDefines;
  85163. if (!defines) {
  85164. return;
  85165. }
  85166. var effect = subMesh.effect;
  85167. if (!effect) {
  85168. return;
  85169. }
  85170. this._activeEffect = effect;
  85171. // Matrices
  85172. this.bindOnlyWorldMatrix(world);
  85173. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  85174. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  85175. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  85176. // Uniforms
  85177. if (this._mustRebind(scene, effect)) {
  85178. this._activeEffect.setColor3("mainColor", this.mainColor);
  85179. this._activeEffect.setColor3("lineColor", this.lineColor);
  85180. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  85181. this._gridControl.x = this.gridRatio;
  85182. this._gridControl.y = Math.round(this.majorUnitFrequency);
  85183. this._gridControl.z = this.minorUnitVisibility;
  85184. this._gridControl.w = this.opacity;
  85185. this._activeEffect.setVector4("gridControl", this._gridControl);
  85186. }
  85187. // Fog
  85188. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85189. this._afterBind(mesh, this._activeEffect);
  85190. };
  85191. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  85192. _super.prototype.dispose.call(this, forceDisposeEffect);
  85193. };
  85194. GridMaterial.prototype.clone = function (name) {
  85195. var _this = this;
  85196. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  85197. };
  85198. GridMaterial.prototype.serialize = function () {
  85199. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85200. serializationObject.customType = "BABYLON.GridMaterial";
  85201. return serializationObject;
  85202. };
  85203. GridMaterial.prototype.getClassName = function () {
  85204. return "GridMaterial";
  85205. };
  85206. GridMaterial.Parse = function (source, scene, rootUrl) {
  85207. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  85208. };
  85209. __decorate([
  85210. BABYLON.serializeAsColor3()
  85211. ], GridMaterial.prototype, "mainColor", void 0);
  85212. __decorate([
  85213. BABYLON.serializeAsColor3()
  85214. ], GridMaterial.prototype, "lineColor", void 0);
  85215. __decorate([
  85216. BABYLON.serialize()
  85217. ], GridMaterial.prototype, "gridRatio", void 0);
  85218. __decorate([
  85219. BABYLON.serializeAsColor3()
  85220. ], GridMaterial.prototype, "gridOffset", void 0);
  85221. __decorate([
  85222. BABYLON.serialize()
  85223. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  85224. __decorate([
  85225. BABYLON.serialize()
  85226. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  85227. __decorate([
  85228. BABYLON.serialize()
  85229. ], GridMaterial.prototype, "opacity", void 0);
  85230. __decorate([
  85231. BABYLON.serialize()
  85232. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  85233. return GridMaterial;
  85234. }(BABYLON.PushMaterial));
  85235. BABYLON.GridMaterial = GridMaterial;
  85236. })(BABYLON || (BABYLON = {}));
  85237. //# sourceMappingURL=babylon.gridmaterial.js.map
  85238. 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}";
  85239. 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}";
  85240. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85241. var BABYLON;
  85242. (function (BABYLON) {
  85243. var GLTFLoaderCoordinateSystemMode;
  85244. (function (GLTFLoaderCoordinateSystemMode) {
  85245. /**
  85246. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  85247. */
  85248. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  85249. /**
  85250. * Sets the useRightHandedSystem flag on the scene.
  85251. */
  85252. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  85253. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  85254. var GLTFLoaderAnimationStartMode;
  85255. (function (GLTFLoaderAnimationStartMode) {
  85256. /**
  85257. * No animation will start.
  85258. */
  85259. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  85260. /**
  85261. * The first animation will start.
  85262. */
  85263. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  85264. /**
  85265. * All animations will start.
  85266. */
  85267. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  85268. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  85269. var GLTFFileLoader = /** @class */ (function () {
  85270. function GLTFFileLoader() {
  85271. // #region Common options
  85272. /**
  85273. * Raised when the asset has been parsed.
  85274. * The data.json property stores the glTF JSON.
  85275. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  85276. */
  85277. this.onParsedObservable = new BABYLON.Observable();
  85278. // #endregion
  85279. // #region V2 options
  85280. /**
  85281. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  85282. */
  85283. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  85284. /**
  85285. * The animation start mode (NONE, FIRST, ALL).
  85286. */
  85287. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  85288. /**
  85289. * Set to true to compile materials before raising the success callback.
  85290. */
  85291. this.compileMaterials = false;
  85292. /**
  85293. * Set to true to also compile materials with clip planes.
  85294. */
  85295. this.useClipPlane = false;
  85296. /**
  85297. * Set to true to compile shadow generators before raising the success callback.
  85298. */
  85299. this.compileShadowGenerators = false;
  85300. /**
  85301. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  85302. */
  85303. this.onMeshLoadedObservable = new BABYLON.Observable();
  85304. /**
  85305. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  85306. */
  85307. this.onTextureLoadedObservable = new BABYLON.Observable();
  85308. /**
  85309. * Raised when the loader creates a material after parsing the glTF properties of the material.
  85310. */
  85311. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85312. /**
  85313. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  85314. * For assets with LODs, raised when all of the LODs are complete.
  85315. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  85316. */
  85317. this.onCompleteObservable = new BABYLON.Observable();
  85318. /**
  85319. * Raised when the loader is disposed.
  85320. */
  85321. this.onDisposeObservable = new BABYLON.Observable();
  85322. // #endregion
  85323. this._loader = null;
  85324. this.name = "gltf";
  85325. this.extensions = {
  85326. ".gltf": { isBinary: false },
  85327. ".glb": { isBinary: true }
  85328. };
  85329. }
  85330. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  85331. set: function (callback) {
  85332. if (this._onParsedObserver) {
  85333. this.onParsedObservable.remove(this._onParsedObserver);
  85334. }
  85335. this._onParsedObserver = this.onParsedObservable.add(callback);
  85336. },
  85337. enumerable: true,
  85338. configurable: true
  85339. });
  85340. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  85341. set: function (callback) {
  85342. if (this._onMeshLoadedObserver) {
  85343. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  85344. }
  85345. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  85346. },
  85347. enumerable: true,
  85348. configurable: true
  85349. });
  85350. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  85351. set: function (callback) {
  85352. if (this._onTextureLoadedObserver) {
  85353. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  85354. }
  85355. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  85356. },
  85357. enumerable: true,
  85358. configurable: true
  85359. });
  85360. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  85361. set: function (callback) {
  85362. if (this._onMaterialLoadedObserver) {
  85363. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  85364. }
  85365. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  85366. },
  85367. enumerable: true,
  85368. configurable: true
  85369. });
  85370. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  85371. set: function (callback) {
  85372. if (this._onCompleteObserver) {
  85373. this.onCompleteObservable.remove(this._onCompleteObserver);
  85374. }
  85375. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  85376. },
  85377. enumerable: true,
  85378. configurable: true
  85379. });
  85380. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  85381. set: function (callback) {
  85382. if (this._onDisposeObserver) {
  85383. this.onDisposeObservable.remove(this._onDisposeObserver);
  85384. }
  85385. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85386. },
  85387. enumerable: true,
  85388. configurable: true
  85389. });
  85390. /**
  85391. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  85392. */
  85393. GLTFFileLoader.prototype.dispose = function () {
  85394. if (this._loader) {
  85395. this._loader.dispose();
  85396. this._loader = null;
  85397. }
  85398. this.onParsedObservable.clear();
  85399. this.onMeshLoadedObservable.clear();
  85400. this.onTextureLoadedObservable.clear();
  85401. this.onMaterialLoadedObservable.clear();
  85402. this.onCompleteObservable.clear();
  85403. this.onDisposeObservable.notifyObservers(this);
  85404. this.onDisposeObservable.clear();
  85405. };
  85406. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85407. try {
  85408. var loaderData = this._parse(data);
  85409. this._loader = this._getLoader(loaderData);
  85410. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85411. }
  85412. catch (e) {
  85413. if (onError) {
  85414. onError(e.message, e);
  85415. }
  85416. else {
  85417. BABYLON.Tools.Error(e.message);
  85418. }
  85419. }
  85420. };
  85421. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85422. try {
  85423. var loaderData = this._parse(data);
  85424. this._loader = this._getLoader(loaderData);
  85425. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85426. }
  85427. catch (e) {
  85428. if (onError) {
  85429. onError(e.message, e);
  85430. }
  85431. else {
  85432. BABYLON.Tools.Error(e.message);
  85433. }
  85434. }
  85435. };
  85436. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85437. try {
  85438. var loaderData = this._parse(data);
  85439. this._loader = this._getLoader(loaderData);
  85440. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  85441. var container = new BABYLON.AssetContainer(scene);
  85442. Array.prototype.push.apply(container.meshes, meshes);
  85443. Array.prototype.push.apply(container.particleSystems, particleSystems);
  85444. Array.prototype.push.apply(container.skeletons, skeletons);
  85445. container.removeAllFromScene();
  85446. onSuccess(container);
  85447. }, onProgress, onError);
  85448. }
  85449. catch (e) {
  85450. if (onError) {
  85451. onError(e.message, e);
  85452. }
  85453. else {
  85454. BABYLON.Tools.Error(e.message);
  85455. }
  85456. }
  85457. };
  85458. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  85459. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  85460. };
  85461. GLTFFileLoader.prototype.createPlugin = function () {
  85462. return new GLTFFileLoader();
  85463. };
  85464. GLTFFileLoader.prototype._parse = function (data) {
  85465. var parsedData;
  85466. if (data instanceof ArrayBuffer) {
  85467. parsedData = GLTFFileLoader._parseBinary(data);
  85468. }
  85469. else {
  85470. parsedData = {
  85471. json: JSON.parse(data),
  85472. bin: null
  85473. };
  85474. }
  85475. this.onParsedObservable.notifyObservers(parsedData);
  85476. return parsedData;
  85477. };
  85478. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  85479. var _this = this;
  85480. var loaderVersion = { major: 2, minor: 0 };
  85481. var asset = loaderData.json.asset || {};
  85482. var version = GLTFFileLoader._parseVersion(asset.version);
  85483. if (!version) {
  85484. throw new Error("Invalid version: " + asset.version);
  85485. }
  85486. if (asset.minVersion !== undefined) {
  85487. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  85488. if (!minVersion) {
  85489. throw new Error("Invalid minimum version: " + asset.minVersion);
  85490. }
  85491. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  85492. throw new Error("Incompatible minimum version: " + asset.minVersion);
  85493. }
  85494. }
  85495. var createLoaders = {
  85496. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  85497. 2: GLTFFileLoader.CreateGLTFLoaderV2
  85498. };
  85499. var createLoader = createLoaders[version.major];
  85500. if (!createLoader) {
  85501. throw new Error("Unsupported version: " + asset.version);
  85502. }
  85503. var loader = createLoader();
  85504. loader.coordinateSystemMode = this.coordinateSystemMode;
  85505. loader.animationStartMode = this.animationStartMode;
  85506. loader.compileMaterials = this.compileMaterials;
  85507. loader.useClipPlane = this.useClipPlane;
  85508. loader.compileShadowGenerators = this.compileShadowGenerators;
  85509. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  85510. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  85511. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  85512. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  85513. return loader;
  85514. };
  85515. GLTFFileLoader._parseBinary = function (data) {
  85516. var Binary = {
  85517. Magic: 0x46546C67
  85518. };
  85519. var binaryReader = new BinaryReader(data);
  85520. var magic = binaryReader.readUint32();
  85521. if (magic !== Binary.Magic) {
  85522. throw new Error("Unexpected magic: " + magic);
  85523. }
  85524. var version = binaryReader.readUint32();
  85525. switch (version) {
  85526. case 1: return GLTFFileLoader._parseV1(binaryReader);
  85527. case 2: return GLTFFileLoader._parseV2(binaryReader);
  85528. }
  85529. throw new Error("Unsupported version: " + version);
  85530. };
  85531. GLTFFileLoader._parseV1 = function (binaryReader) {
  85532. var ContentFormat = {
  85533. JSON: 0
  85534. };
  85535. var length = binaryReader.readUint32();
  85536. if (length != binaryReader.getLength()) {
  85537. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85538. }
  85539. var contentLength = binaryReader.readUint32();
  85540. var contentFormat = binaryReader.readUint32();
  85541. var content;
  85542. switch (contentFormat) {
  85543. case ContentFormat.JSON: {
  85544. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  85545. break;
  85546. }
  85547. default: {
  85548. throw new Error("Unexpected content format: " + contentFormat);
  85549. }
  85550. }
  85551. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  85552. var body = binaryReader.readUint8Array(bytesRemaining);
  85553. return {
  85554. json: content,
  85555. bin: body
  85556. };
  85557. };
  85558. GLTFFileLoader._parseV2 = function (binaryReader) {
  85559. var ChunkFormat = {
  85560. JSON: 0x4E4F534A,
  85561. BIN: 0x004E4942
  85562. };
  85563. var length = binaryReader.readUint32();
  85564. if (length !== binaryReader.getLength()) {
  85565. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85566. }
  85567. // JSON chunk
  85568. var chunkLength = binaryReader.readUint32();
  85569. var chunkFormat = binaryReader.readUint32();
  85570. if (chunkFormat !== ChunkFormat.JSON) {
  85571. throw new Error("First chunk format is not JSON");
  85572. }
  85573. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  85574. // Look for BIN chunk
  85575. var bin = null;
  85576. while (binaryReader.getPosition() < binaryReader.getLength()) {
  85577. var chunkLength_1 = binaryReader.readUint32();
  85578. var chunkFormat_1 = binaryReader.readUint32();
  85579. switch (chunkFormat_1) {
  85580. case ChunkFormat.JSON: {
  85581. throw new Error("Unexpected JSON chunk");
  85582. }
  85583. case ChunkFormat.BIN: {
  85584. bin = binaryReader.readUint8Array(chunkLength_1);
  85585. break;
  85586. }
  85587. default: {
  85588. // ignore unrecognized chunkFormat
  85589. binaryReader.skipBytes(chunkLength_1);
  85590. break;
  85591. }
  85592. }
  85593. }
  85594. return {
  85595. json: json,
  85596. bin: bin
  85597. };
  85598. };
  85599. GLTFFileLoader._parseVersion = function (version) {
  85600. if (version === "1.0" || version === "1.0.1") {
  85601. return {
  85602. major: 1,
  85603. minor: 0
  85604. };
  85605. }
  85606. var match = (version + "").match(/^(\d+)\.(\d+)/);
  85607. if (!match) {
  85608. return null;
  85609. }
  85610. return {
  85611. major: parseInt(match[1]),
  85612. minor: parseInt(match[2])
  85613. };
  85614. };
  85615. GLTFFileLoader._compareVersion = function (a, b) {
  85616. if (a.major > b.major)
  85617. return 1;
  85618. if (a.major < b.major)
  85619. return -1;
  85620. if (a.minor > b.minor)
  85621. return 1;
  85622. if (a.minor < b.minor)
  85623. return -1;
  85624. return 0;
  85625. };
  85626. GLTFFileLoader._decodeBufferToText = function (buffer) {
  85627. var result = "";
  85628. var length = buffer.byteLength;
  85629. for (var i = 0; i < length; i++) {
  85630. result += String.fromCharCode(buffer[i]);
  85631. }
  85632. return result;
  85633. };
  85634. // #endregion
  85635. // #region V1 options
  85636. GLTFFileLoader.IncrementalLoading = true;
  85637. GLTFFileLoader.HomogeneousCoordinates = false;
  85638. return GLTFFileLoader;
  85639. }());
  85640. BABYLON.GLTFFileLoader = GLTFFileLoader;
  85641. var BinaryReader = /** @class */ (function () {
  85642. function BinaryReader(arrayBuffer) {
  85643. this._arrayBuffer = arrayBuffer;
  85644. this._dataView = new DataView(arrayBuffer);
  85645. this._byteOffset = 0;
  85646. }
  85647. BinaryReader.prototype.getPosition = function () {
  85648. return this._byteOffset;
  85649. };
  85650. BinaryReader.prototype.getLength = function () {
  85651. return this._arrayBuffer.byteLength;
  85652. };
  85653. BinaryReader.prototype.readUint32 = function () {
  85654. var value = this._dataView.getUint32(this._byteOffset, true);
  85655. this._byteOffset += 4;
  85656. return value;
  85657. };
  85658. BinaryReader.prototype.readUint8Array = function (length) {
  85659. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  85660. this._byteOffset += length;
  85661. return value;
  85662. };
  85663. BinaryReader.prototype.skipBytes = function (length) {
  85664. this._byteOffset += length;
  85665. };
  85666. return BinaryReader;
  85667. }());
  85668. if (BABYLON.SceneLoader) {
  85669. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  85670. }
  85671. })(BABYLON || (BABYLON = {}));
  85672. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  85673. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85674. var BABYLON;
  85675. (function (BABYLON) {
  85676. var GLTF1;
  85677. (function (GLTF1) {
  85678. /**
  85679. * Enums
  85680. */
  85681. var EComponentType;
  85682. (function (EComponentType) {
  85683. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  85684. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  85685. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  85686. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  85687. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  85688. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  85689. var EShaderType;
  85690. (function (EShaderType) {
  85691. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  85692. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  85693. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  85694. var EParameterType;
  85695. (function (EParameterType) {
  85696. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  85697. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  85698. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  85699. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  85700. EParameterType[EParameterType["INT"] = 5124] = "INT";
  85701. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  85702. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  85703. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  85704. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  85705. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  85706. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  85707. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  85708. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  85709. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  85710. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  85711. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  85712. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  85713. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  85714. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  85715. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  85716. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  85717. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  85718. var ETextureWrapMode;
  85719. (function (ETextureWrapMode) {
  85720. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  85721. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  85722. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  85723. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  85724. var ETextureFilterType;
  85725. (function (ETextureFilterType) {
  85726. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  85727. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  85728. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  85729. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  85730. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  85731. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  85732. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  85733. var ETextureFormat;
  85734. (function (ETextureFormat) {
  85735. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  85736. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  85737. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  85738. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  85739. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  85740. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  85741. var ECullingType;
  85742. (function (ECullingType) {
  85743. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  85744. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  85745. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  85746. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  85747. var EBlendingFunction;
  85748. (function (EBlendingFunction) {
  85749. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  85750. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  85751. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  85752. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  85753. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  85754. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  85755. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  85756. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  85757. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  85758. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  85759. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  85760. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  85761. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  85762. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  85763. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  85764. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  85765. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85766. })(BABYLON || (BABYLON = {}));
  85767. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  85768. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85769. var BABYLON;
  85770. (function (BABYLON) {
  85771. var GLTF1;
  85772. (function (GLTF1) {
  85773. /**
  85774. * Tokenizer. Used for shaders compatibility
  85775. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  85776. */
  85777. var ETokenType;
  85778. (function (ETokenType) {
  85779. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  85780. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  85781. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  85782. })(ETokenType || (ETokenType = {}));
  85783. var Tokenizer = /** @class */ (function () {
  85784. function Tokenizer(toParse) {
  85785. this._pos = 0;
  85786. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  85787. this._toParse = toParse;
  85788. this._maxPos = toParse.length;
  85789. }
  85790. Tokenizer.prototype.getNextToken = function () {
  85791. if (this.isEnd())
  85792. return ETokenType.END_OF_INPUT;
  85793. this.currentString = this.read();
  85794. this.currentToken = ETokenType.UNKNOWN;
  85795. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  85796. this.currentToken = ETokenType.IDENTIFIER;
  85797. this.currentIdentifier = this.currentString;
  85798. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  85799. this.currentIdentifier += this.currentString;
  85800. this.forward();
  85801. }
  85802. }
  85803. return this.currentToken;
  85804. };
  85805. Tokenizer.prototype.peek = function () {
  85806. return this._toParse[this._pos];
  85807. };
  85808. Tokenizer.prototype.read = function () {
  85809. return this._toParse[this._pos++];
  85810. };
  85811. Tokenizer.prototype.forward = function () {
  85812. this._pos++;
  85813. };
  85814. Tokenizer.prototype.isEnd = function () {
  85815. return this._pos >= this._maxPos;
  85816. };
  85817. return Tokenizer;
  85818. }());
  85819. /**
  85820. * Values
  85821. */
  85822. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  85823. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  85824. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  85825. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  85826. /**
  85827. * Parse
  85828. */
  85829. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  85830. for (var buf in parsedBuffers) {
  85831. var parsedBuffer = parsedBuffers[buf];
  85832. gltfRuntime.buffers[buf] = parsedBuffer;
  85833. gltfRuntime.buffersCount++;
  85834. }
  85835. };
  85836. var parseShaders = function (parsedShaders, gltfRuntime) {
  85837. for (var sha in parsedShaders) {
  85838. var parsedShader = parsedShaders[sha];
  85839. gltfRuntime.shaders[sha] = parsedShader;
  85840. gltfRuntime.shaderscount++;
  85841. }
  85842. };
  85843. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  85844. for (var object in parsedObjects) {
  85845. var parsedObject = parsedObjects[object];
  85846. gltfRuntime[runtimeProperty][object] = parsedObject;
  85847. }
  85848. };
  85849. /**
  85850. * Utils
  85851. */
  85852. var normalizeUVs = function (buffer) {
  85853. if (!buffer) {
  85854. return;
  85855. }
  85856. for (var i = 0; i < buffer.length / 2; i++) {
  85857. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  85858. }
  85859. };
  85860. var getAttribute = function (attributeParameter) {
  85861. if (attributeParameter.semantic === "NORMAL") {
  85862. return "normal";
  85863. }
  85864. else if (attributeParameter.semantic === "POSITION") {
  85865. return "position";
  85866. }
  85867. else if (attributeParameter.semantic === "JOINT") {
  85868. return "matricesIndices";
  85869. }
  85870. else if (attributeParameter.semantic === "WEIGHT") {
  85871. return "matricesWeights";
  85872. }
  85873. else if (attributeParameter.semantic === "COLOR") {
  85874. return "color";
  85875. }
  85876. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  85877. var channel = Number(attributeParameter.semantic.split("_")[1]);
  85878. return "uv" + (channel === 0 ? "" : channel + 1);
  85879. }
  85880. return null;
  85881. };
  85882. /**
  85883. * Loads and creates animations
  85884. */
  85885. var loadAnimations = function (gltfRuntime) {
  85886. for (var anim in gltfRuntime.animations) {
  85887. var animation = gltfRuntime.animations[anim];
  85888. if (!animation.channels || !animation.samplers) {
  85889. continue;
  85890. }
  85891. var lastAnimation = null;
  85892. for (var i = 0; i < animation.channels.length; i++) {
  85893. // Get parameters and load buffers
  85894. var channel = animation.channels[i];
  85895. var sampler = animation.samplers[channel.sampler];
  85896. if (!sampler) {
  85897. continue;
  85898. }
  85899. var inputData = null;
  85900. var outputData = null;
  85901. if (animation.parameters) {
  85902. inputData = animation.parameters[sampler.input];
  85903. outputData = animation.parameters[sampler.output];
  85904. }
  85905. else {
  85906. inputData = sampler.input;
  85907. outputData = sampler.output;
  85908. }
  85909. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  85910. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  85911. var targetID = channel.target.id;
  85912. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  85913. if (targetNode === null) {
  85914. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  85915. }
  85916. if (targetNode === null) {
  85917. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  85918. continue;
  85919. }
  85920. var isBone = targetNode instanceof BABYLON.Bone;
  85921. // Get target path (position, rotation or scaling)
  85922. var targetPath = channel.target.path;
  85923. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  85924. if (targetPathIndex !== -1) {
  85925. targetPath = babylonAnimationPaths[targetPathIndex];
  85926. }
  85927. // Determine animation type
  85928. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  85929. if (!isBone) {
  85930. if (targetPath === "rotationQuaternion") {
  85931. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85932. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  85933. }
  85934. else {
  85935. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85936. }
  85937. }
  85938. // Create animation and key frames
  85939. var babylonAnimation = null;
  85940. var keys = [];
  85941. var arrayOffset = 0;
  85942. var modifyKey = false;
  85943. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  85944. babylonAnimation = lastAnimation;
  85945. modifyKey = true;
  85946. }
  85947. if (!modifyKey) {
  85948. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  85949. }
  85950. // For each frame
  85951. for (var j = 0; j < bufferInput.length; j++) {
  85952. var value = null;
  85953. if (targetPath === "rotationQuaternion") {
  85954. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  85955. arrayOffset += 4;
  85956. }
  85957. else {
  85958. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  85959. arrayOffset += 3;
  85960. }
  85961. if (isBone) {
  85962. var bone = targetNode;
  85963. var translation = BABYLON.Vector3.Zero();
  85964. var rotationQuaternion = new BABYLON.Quaternion();
  85965. var scaling = BABYLON.Vector3.Zero();
  85966. // Warning on decompose
  85967. var mat = bone.getBaseMatrix();
  85968. if (modifyKey && lastAnimation) {
  85969. mat = lastAnimation.getKeys()[j].value;
  85970. }
  85971. mat.decompose(scaling, rotationQuaternion, translation);
  85972. if (targetPath === "position") {
  85973. translation = value;
  85974. }
  85975. else if (targetPath === "rotationQuaternion") {
  85976. rotationQuaternion = value;
  85977. }
  85978. else {
  85979. scaling = value;
  85980. }
  85981. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  85982. }
  85983. if (!modifyKey) {
  85984. keys.push({
  85985. frame: bufferInput[j],
  85986. value: value
  85987. });
  85988. }
  85989. else if (lastAnimation) {
  85990. lastAnimation.getKeys()[j].value = value;
  85991. }
  85992. }
  85993. // Finish
  85994. if (!modifyKey && babylonAnimation) {
  85995. babylonAnimation.setKeys(keys);
  85996. targetNode.animations.push(babylonAnimation);
  85997. }
  85998. lastAnimation = babylonAnimation;
  85999. gltfRuntime.scene.stopAnimation(targetNode);
  86000. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  86001. }
  86002. }
  86003. };
  86004. /**
  86005. * Returns the bones transformation matrix
  86006. */
  86007. var configureBoneTransformation = function (node) {
  86008. var mat = null;
  86009. if (node.translation || node.rotation || node.scale) {
  86010. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  86011. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  86012. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  86013. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  86014. }
  86015. else {
  86016. mat = BABYLON.Matrix.FromArray(node.matrix);
  86017. }
  86018. return mat;
  86019. };
  86020. /**
  86021. * Returns the parent bone
  86022. */
  86023. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  86024. // Try to find
  86025. for (var i = 0; i < newSkeleton.bones.length; i++) {
  86026. if (newSkeleton.bones[i].name === jointName) {
  86027. return newSkeleton.bones[i];
  86028. }
  86029. }
  86030. // Not found, search in gltf nodes
  86031. var nodes = gltfRuntime.nodes;
  86032. for (var nde in nodes) {
  86033. var node = nodes[nde];
  86034. if (!node.jointName) {
  86035. continue;
  86036. }
  86037. var children = node.children;
  86038. for (var i = 0; i < children.length; i++) {
  86039. var child = gltfRuntime.nodes[children[i]];
  86040. if (!child.jointName) {
  86041. continue;
  86042. }
  86043. if (child.jointName === jointName) {
  86044. var mat = configureBoneTransformation(node);
  86045. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  86046. bone.id = nde;
  86047. return bone;
  86048. }
  86049. }
  86050. }
  86051. return null;
  86052. };
  86053. /**
  86054. * Returns the appropriate root node
  86055. */
  86056. var getNodeToRoot = function (nodesToRoot, id) {
  86057. for (var i = 0; i < nodesToRoot.length; i++) {
  86058. var nodeToRoot = nodesToRoot[i];
  86059. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  86060. var child = nodeToRoot.node.children[j];
  86061. if (child === id) {
  86062. return nodeToRoot.bone;
  86063. }
  86064. }
  86065. }
  86066. return null;
  86067. };
  86068. /**
  86069. * Returns the node with the joint name
  86070. */
  86071. var getJointNode = function (gltfRuntime, jointName) {
  86072. var nodes = gltfRuntime.nodes;
  86073. var node = nodes[jointName];
  86074. if (node) {
  86075. return {
  86076. node: node,
  86077. id: jointName
  86078. };
  86079. }
  86080. for (var nde in nodes) {
  86081. node = nodes[nde];
  86082. if (node.jointName === jointName) {
  86083. return {
  86084. node: node,
  86085. id: nde
  86086. };
  86087. }
  86088. }
  86089. return null;
  86090. };
  86091. /**
  86092. * Checks if a nodes is in joints
  86093. */
  86094. var nodeIsInJoints = function (skins, id) {
  86095. for (var i = 0; i < skins.jointNames.length; i++) {
  86096. if (skins.jointNames[i] === id) {
  86097. return true;
  86098. }
  86099. }
  86100. return false;
  86101. };
  86102. /**
  86103. * Fills the nodes to root for bones and builds hierarchy
  86104. */
  86105. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  86106. // Creates nodes for root
  86107. for (var nde in gltfRuntime.nodes) {
  86108. var node = gltfRuntime.nodes[nde];
  86109. var id = nde;
  86110. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  86111. continue;
  86112. }
  86113. // Create node to root bone
  86114. var mat = configureBoneTransformation(node);
  86115. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  86116. bone.id = id;
  86117. nodesToRoot.push({ bone: bone, node: node, id: id });
  86118. }
  86119. // Parenting
  86120. for (var i = 0; i < nodesToRoot.length; i++) {
  86121. var nodeToRoot = nodesToRoot[i];
  86122. var children = nodeToRoot.node.children;
  86123. for (var j = 0; j < children.length; j++) {
  86124. var child = null;
  86125. for (var k = 0; k < nodesToRoot.length; k++) {
  86126. if (nodesToRoot[k].id === children[j]) {
  86127. child = nodesToRoot[k];
  86128. break;
  86129. }
  86130. }
  86131. if (child) {
  86132. child.bone._parent = nodeToRoot.bone;
  86133. nodeToRoot.bone.children.push(child.bone);
  86134. }
  86135. }
  86136. }
  86137. };
  86138. /**
  86139. * Imports a skeleton
  86140. */
  86141. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  86142. if (!newSkeleton) {
  86143. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  86144. }
  86145. if (!skins.babylonSkeleton) {
  86146. return newSkeleton;
  86147. }
  86148. // Find the root bones
  86149. var nodesToRoot = [];
  86150. var nodesToRootToAdd = [];
  86151. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  86152. newSkeleton.bones = [];
  86153. // Joints
  86154. for (var i = 0; i < skins.jointNames.length; i++) {
  86155. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86156. if (!jointNode) {
  86157. continue;
  86158. }
  86159. var node = jointNode.node;
  86160. if (!node) {
  86161. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  86162. continue;
  86163. }
  86164. var id = jointNode.id;
  86165. // Optimize, if the bone already exists...
  86166. var existingBone = gltfRuntime.scene.getBoneByID(id);
  86167. if (existingBone) {
  86168. newSkeleton.bones.push(existingBone);
  86169. continue;
  86170. }
  86171. // Search for parent bone
  86172. var foundBone = false;
  86173. var parentBone = null;
  86174. for (var j = 0; j < i; j++) {
  86175. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  86176. if (!jointNode_1) {
  86177. continue;
  86178. }
  86179. var joint = jointNode_1.node;
  86180. if (!joint) {
  86181. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  86182. continue;
  86183. }
  86184. var children = joint.children;
  86185. if (!children) {
  86186. continue;
  86187. }
  86188. foundBone = false;
  86189. for (var k = 0; k < children.length; k++) {
  86190. if (children[k] === id) {
  86191. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  86192. foundBone = true;
  86193. break;
  86194. }
  86195. }
  86196. if (foundBone) {
  86197. break;
  86198. }
  86199. }
  86200. // Create bone
  86201. var mat = configureBoneTransformation(node);
  86202. if (!parentBone && nodesToRoot.length > 0) {
  86203. parentBone = getNodeToRoot(nodesToRoot, id);
  86204. if (parentBone) {
  86205. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  86206. nodesToRootToAdd.push(parentBone);
  86207. }
  86208. }
  86209. }
  86210. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  86211. bone.id = id;
  86212. }
  86213. // Polish
  86214. var bones = newSkeleton.bones;
  86215. newSkeleton.bones = [];
  86216. for (var i = 0; i < skins.jointNames.length; i++) {
  86217. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86218. if (!jointNode) {
  86219. continue;
  86220. }
  86221. for (var j = 0; j < bones.length; j++) {
  86222. if (bones[j].id === jointNode.id) {
  86223. newSkeleton.bones.push(bones[j]);
  86224. break;
  86225. }
  86226. }
  86227. }
  86228. newSkeleton.prepare();
  86229. // Finish
  86230. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  86231. newSkeleton.bones.push(nodesToRootToAdd[i]);
  86232. }
  86233. return newSkeleton;
  86234. };
  86235. /**
  86236. * Imports a mesh and its geometries
  86237. */
  86238. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  86239. if (!newMesh) {
  86240. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86241. newMesh.id = id;
  86242. }
  86243. if (!node.babylonNode) {
  86244. return newMesh;
  86245. }
  86246. var subMaterials = [];
  86247. var vertexData = new BABYLON.VertexData();
  86248. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  86249. var verticesStarts = new Array();
  86250. var verticesCounts = new Array();
  86251. var indexStarts = new Array();
  86252. var indexCounts = new Array();
  86253. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86254. var meshID = meshes[meshIndex];
  86255. var mesh = gltfRuntime.meshes[meshID];
  86256. if (!mesh) {
  86257. continue;
  86258. }
  86259. // Positions, normals and UVs
  86260. for (var i = 0; i < mesh.primitives.length; i++) {
  86261. // Temporary vertex data
  86262. var tempVertexData = new BABYLON.VertexData();
  86263. var primitive = mesh.primitives[i];
  86264. if (primitive.mode !== 4) {
  86265. // continue;
  86266. }
  86267. var attributes = primitive.attributes;
  86268. var accessor = null;
  86269. var buffer = null;
  86270. // Set positions, normal and uvs
  86271. for (var semantic in attributes) {
  86272. // Link accessor and buffer view
  86273. accessor = gltfRuntime.accessors[attributes[semantic]];
  86274. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86275. if (semantic === "NORMAL") {
  86276. tempVertexData.normals = new Float32Array(buffer.length);
  86277. tempVertexData.normals.set(buffer);
  86278. }
  86279. else if (semantic === "POSITION") {
  86280. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  86281. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  86282. for (var j = 0; j < buffer.length; j += 4) {
  86283. tempVertexData.positions[j] = buffer[j];
  86284. tempVertexData.positions[j + 1] = buffer[j + 1];
  86285. tempVertexData.positions[j + 2] = buffer[j + 2];
  86286. }
  86287. }
  86288. else {
  86289. tempVertexData.positions = new Float32Array(buffer.length);
  86290. tempVertexData.positions.set(buffer);
  86291. }
  86292. verticesCounts.push(tempVertexData.positions.length);
  86293. }
  86294. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  86295. var channel = Number(semantic.split("_")[1]);
  86296. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  86297. var uvs = new Float32Array(buffer.length);
  86298. uvs.set(buffer);
  86299. normalizeUVs(uvs);
  86300. tempVertexData.set(uvs, uvKind);
  86301. }
  86302. else if (semantic === "JOINT") {
  86303. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  86304. tempVertexData.matricesIndices.set(buffer);
  86305. }
  86306. else if (semantic === "WEIGHT") {
  86307. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  86308. tempVertexData.matricesWeights.set(buffer);
  86309. }
  86310. else if (semantic === "COLOR") {
  86311. tempVertexData.colors = new Float32Array(buffer.length);
  86312. tempVertexData.colors.set(buffer);
  86313. }
  86314. }
  86315. // Indices
  86316. accessor = gltfRuntime.accessors[primitive.indices];
  86317. if (accessor) {
  86318. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86319. tempVertexData.indices = new Int32Array(buffer.length);
  86320. tempVertexData.indices.set(buffer);
  86321. indexCounts.push(tempVertexData.indices.length);
  86322. }
  86323. else {
  86324. // Set indices on the fly
  86325. var indices = [];
  86326. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  86327. indices.push(j);
  86328. }
  86329. tempVertexData.indices = new Int32Array(indices);
  86330. indexCounts.push(tempVertexData.indices.length);
  86331. }
  86332. vertexData.merge(tempVertexData);
  86333. // Sub material
  86334. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  86335. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  86336. // Update vertices start and index start
  86337. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  86338. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  86339. }
  86340. }
  86341. var material;
  86342. if (subMaterials.length > 1) {
  86343. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  86344. material.subMaterials = subMaterials;
  86345. }
  86346. else {
  86347. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  86348. }
  86349. if (subMaterials.length === 1) {
  86350. material = subMaterials[0];
  86351. }
  86352. if (!newMesh.material) {
  86353. newMesh.material = material;
  86354. }
  86355. // Apply geometry
  86356. geometry.setAllVerticesData(vertexData, false);
  86357. newMesh.computeWorldMatrix(true);
  86358. // Apply submeshes
  86359. newMesh.subMeshes = [];
  86360. var index = 0;
  86361. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86362. var meshID = meshes[meshIndex];
  86363. var mesh = gltfRuntime.meshes[meshID];
  86364. if (!mesh) {
  86365. continue;
  86366. }
  86367. for (var i = 0; i < mesh.primitives.length; i++) {
  86368. if (mesh.primitives[i].mode !== 4) {
  86369. //continue;
  86370. }
  86371. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  86372. index++;
  86373. }
  86374. }
  86375. // Finish
  86376. return newMesh;
  86377. };
  86378. /**
  86379. * Configure node transformation from position, rotation and scaling
  86380. */
  86381. var configureNode = function (newNode, position, rotation, scaling) {
  86382. if (newNode.position) {
  86383. newNode.position = position;
  86384. }
  86385. if (newNode.rotationQuaternion || newNode.rotation) {
  86386. newNode.rotationQuaternion = rotation;
  86387. }
  86388. if (newNode.scaling) {
  86389. newNode.scaling = scaling;
  86390. }
  86391. };
  86392. /**
  86393. * Configures node from transformation matrix
  86394. */
  86395. var configureNodeFromMatrix = function (newNode, node, parent) {
  86396. if (node.matrix) {
  86397. var position = new BABYLON.Vector3(0, 0, 0);
  86398. var rotation = new BABYLON.Quaternion();
  86399. var scaling = new BABYLON.Vector3(0, 0, 0);
  86400. var mat = BABYLON.Matrix.FromArray(node.matrix);
  86401. mat.decompose(scaling, rotation, position);
  86402. configureNode(newNode, position, rotation, scaling);
  86403. }
  86404. else if (node.translation && node.rotation && node.scale) {
  86405. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  86406. }
  86407. newNode.computeWorldMatrix(true);
  86408. };
  86409. /**
  86410. * Imports a node
  86411. */
  86412. var importNode = function (gltfRuntime, node, id, parent) {
  86413. var lastNode = null;
  86414. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  86415. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  86416. return null;
  86417. }
  86418. }
  86419. // Meshes
  86420. if (node.skin) {
  86421. if (node.meshes) {
  86422. var skin = gltfRuntime.skins[node.skin];
  86423. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  86424. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  86425. if (newMesh.skeleton === null) {
  86426. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  86427. if (!skin.babylonSkeleton) {
  86428. skin.babylonSkeleton = newMesh.skeleton;
  86429. }
  86430. }
  86431. lastNode = newMesh;
  86432. }
  86433. }
  86434. else if (node.meshes) {
  86435. /**
  86436. * Improve meshes property
  86437. */
  86438. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  86439. lastNode = newMesh;
  86440. }
  86441. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86442. var light = gltfRuntime.lights[node.light];
  86443. if (light) {
  86444. if (light.type === "ambient") {
  86445. var ambienLight = light[light.type];
  86446. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86447. hemiLight.name = node.name || "";
  86448. if (ambienLight.color) {
  86449. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  86450. }
  86451. lastNode = hemiLight;
  86452. }
  86453. else if (light.type === "directional") {
  86454. var directionalLight = light[light.type];
  86455. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86456. dirLight.name = node.name || "";
  86457. if (directionalLight.color) {
  86458. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  86459. }
  86460. lastNode = dirLight;
  86461. }
  86462. else if (light.type === "point") {
  86463. var pointLight = light[light.type];
  86464. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86465. ptLight.name = node.name || "";
  86466. if (pointLight.color) {
  86467. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  86468. }
  86469. lastNode = ptLight;
  86470. }
  86471. else if (light.type === "spot") {
  86472. var spotLight = light[light.type];
  86473. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  86474. spLight.name = node.name || "";
  86475. if (spotLight.color) {
  86476. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  86477. }
  86478. if (spotLight.fallOfAngle) {
  86479. spLight.angle = spotLight.fallOfAngle;
  86480. }
  86481. if (spotLight.fallOffExponent) {
  86482. spLight.exponent = spotLight.fallOffExponent;
  86483. }
  86484. lastNode = spLight;
  86485. }
  86486. }
  86487. }
  86488. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86489. var camera = gltfRuntime.cameras[node.camera];
  86490. if (camera) {
  86491. if (camera.type === "orthographic") {
  86492. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86493. orthoCamera.name = node.name || "";
  86494. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  86495. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86496. lastNode = orthoCamera;
  86497. }
  86498. else if (camera.type === "perspective") {
  86499. var perspectiveCamera = camera[camera.type];
  86500. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86501. persCamera.name = node.name || "";
  86502. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86503. if (!perspectiveCamera.aspectRatio) {
  86504. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  86505. }
  86506. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  86507. persCamera.maxZ = perspectiveCamera.zfar;
  86508. persCamera.minZ = perspectiveCamera.znear;
  86509. }
  86510. lastNode = persCamera;
  86511. }
  86512. }
  86513. }
  86514. // Empty node
  86515. if (!node.jointName) {
  86516. if (node.babylonNode) {
  86517. return node.babylonNode;
  86518. }
  86519. else if (lastNode === null) {
  86520. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86521. node.babylonNode = dummy;
  86522. lastNode = dummy;
  86523. }
  86524. }
  86525. if (lastNode !== null) {
  86526. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  86527. configureNodeFromMatrix(lastNode, node, parent);
  86528. }
  86529. else {
  86530. var translation = node.translation || [0, 0, 0];
  86531. var rotation = node.rotation || [0, 0, 0, 1];
  86532. var scale = node.scale || [1, 1, 1];
  86533. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  86534. }
  86535. lastNode.updateCache(true);
  86536. node.babylonNode = lastNode;
  86537. }
  86538. return lastNode;
  86539. };
  86540. /**
  86541. * Traverses nodes and creates them
  86542. */
  86543. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  86544. if (meshIncluded === void 0) { meshIncluded = false; }
  86545. var node = gltfRuntime.nodes[id];
  86546. var newNode = null;
  86547. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  86548. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  86549. meshIncluded = true;
  86550. }
  86551. else {
  86552. meshIncluded = false;
  86553. }
  86554. }
  86555. else {
  86556. meshIncluded = true;
  86557. }
  86558. if (!node.jointName && meshIncluded) {
  86559. newNode = importNode(gltfRuntime, node, id, parent);
  86560. if (newNode !== null) {
  86561. newNode.id = id;
  86562. newNode.parent = parent;
  86563. }
  86564. }
  86565. if (node.children) {
  86566. for (var i = 0; i < node.children.length; i++) {
  86567. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  86568. }
  86569. }
  86570. };
  86571. /**
  86572. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  86573. */
  86574. var postLoad = function (gltfRuntime) {
  86575. // Nodes
  86576. var currentScene = gltfRuntime.currentScene;
  86577. if (currentScene) {
  86578. for (var i = 0; i < currentScene.nodes.length; i++) {
  86579. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86580. }
  86581. }
  86582. else {
  86583. for (var thing in gltfRuntime.scenes) {
  86584. currentScene = gltfRuntime.scenes[thing];
  86585. for (var i = 0; i < currentScene.nodes.length; i++) {
  86586. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86587. }
  86588. }
  86589. }
  86590. // Set animations
  86591. loadAnimations(gltfRuntime);
  86592. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  86593. var skeleton = gltfRuntime.scene.skeletons[i];
  86594. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  86595. }
  86596. };
  86597. /**
  86598. * onBind shaderrs callback to set uniforms and matrices
  86599. */
  86600. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  86601. var materialValues = material.values || technique.parameters;
  86602. for (var unif in unTreatedUniforms) {
  86603. var uniform = unTreatedUniforms[unif];
  86604. var type = uniform.type;
  86605. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  86606. if (uniform.semantic && !uniform.source && !uniform.node) {
  86607. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  86608. }
  86609. else if (uniform.semantic && (uniform.source || uniform.node)) {
  86610. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  86611. if (source === null) {
  86612. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  86613. }
  86614. if (source === null) {
  86615. continue;
  86616. }
  86617. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  86618. }
  86619. }
  86620. else {
  86621. var value = materialValues[technique.uniforms[unif]];
  86622. if (!value) {
  86623. continue;
  86624. }
  86625. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  86626. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  86627. if (texture === null || texture === undefined) {
  86628. continue;
  86629. }
  86630. shaderMaterial.getEffect().setTexture(unif, texture);
  86631. }
  86632. else {
  86633. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  86634. }
  86635. }
  86636. }
  86637. onSuccess(shaderMaterial);
  86638. };
  86639. /**
  86640. * Prepare uniforms to send the only one time
  86641. * Loads the appropriate textures
  86642. */
  86643. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  86644. var materialValues = material.values || technique.parameters;
  86645. var techniqueUniforms = technique.uniforms;
  86646. /**
  86647. * Prepare values here (not matrices)
  86648. */
  86649. for (var unif in unTreatedUniforms) {
  86650. var uniform = unTreatedUniforms[unif];
  86651. var type = uniform.type;
  86652. var value = materialValues[techniqueUniforms[unif]];
  86653. if (value === undefined) {
  86654. // In case the value is the same for all materials
  86655. value = uniform.value;
  86656. }
  86657. if (!value) {
  86658. continue;
  86659. }
  86660. var onLoadTexture = function (uniformName) {
  86661. return function (texture) {
  86662. if (uniform.value && uniformName) {
  86663. // Static uniform
  86664. shaderMaterial.setTexture(uniformName, texture);
  86665. delete unTreatedUniforms[uniformName];
  86666. }
  86667. };
  86668. };
  86669. // Texture (sampler2D)
  86670. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  86671. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  86672. }
  86673. else {
  86674. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  86675. // Static uniform
  86676. delete unTreatedUniforms[unif];
  86677. }
  86678. }
  86679. }
  86680. };
  86681. /**
  86682. * Shader compilation failed
  86683. */
  86684. var onShaderCompileError = function (program, shaderMaterial, onError) {
  86685. return function (effect, error) {
  86686. shaderMaterial.dispose(true);
  86687. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  86688. };
  86689. };
  86690. /**
  86691. * Shader compilation success
  86692. */
  86693. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  86694. return function (_) {
  86695. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  86696. shaderMaterial.onBind = function (mesh) {
  86697. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  86698. };
  86699. };
  86700. };
  86701. /**
  86702. * Returns the appropriate uniform if already handled by babylon
  86703. */
  86704. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  86705. for (var unif in technique.uniforms) {
  86706. var uniform = technique.uniforms[unif];
  86707. var uniformParameter = technique.parameters[uniform];
  86708. if (tokenizer.currentIdentifier === unif) {
  86709. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  86710. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  86711. if (transformIndex !== -1) {
  86712. delete unTreatedUniforms[unif];
  86713. return babylonTransforms[transformIndex];
  86714. }
  86715. }
  86716. }
  86717. }
  86718. return tokenizer.currentIdentifier;
  86719. };
  86720. /**
  86721. * All shaders loaded. Create materials one by one
  86722. */
  86723. var importMaterials = function (gltfRuntime) {
  86724. // Create materials
  86725. for (var mat in gltfRuntime.materials) {
  86726. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  86727. }
  86728. };
  86729. /**
  86730. * Implementation of the base glTF spec
  86731. */
  86732. var GLTFLoaderBase = /** @class */ (function () {
  86733. function GLTFLoaderBase() {
  86734. }
  86735. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  86736. var gltfRuntime = {
  86737. extensions: {},
  86738. accessors: {},
  86739. buffers: {},
  86740. bufferViews: {},
  86741. meshes: {},
  86742. lights: {},
  86743. cameras: {},
  86744. nodes: {},
  86745. images: {},
  86746. textures: {},
  86747. shaders: {},
  86748. programs: {},
  86749. samplers: {},
  86750. techniques: {},
  86751. materials: {},
  86752. animations: {},
  86753. skins: {},
  86754. extensionsUsed: [],
  86755. scenes: {},
  86756. buffersCount: 0,
  86757. shaderscount: 0,
  86758. scene: scene,
  86759. rootUrl: rootUrl,
  86760. loadedBufferCount: 0,
  86761. loadedBufferViews: {},
  86762. loadedShaderCount: 0,
  86763. importOnlyMeshes: false,
  86764. dummyNodes: []
  86765. };
  86766. // Parse
  86767. if (parsedData.extensions) {
  86768. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  86769. }
  86770. if (parsedData.extensionsUsed) {
  86771. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  86772. }
  86773. if (parsedData.buffers) {
  86774. parseBuffers(parsedData.buffers, gltfRuntime);
  86775. }
  86776. if (parsedData.bufferViews) {
  86777. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  86778. }
  86779. if (parsedData.accessors) {
  86780. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  86781. }
  86782. if (parsedData.meshes) {
  86783. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  86784. }
  86785. if (parsedData.lights) {
  86786. parseObject(parsedData.lights, "lights", gltfRuntime);
  86787. }
  86788. if (parsedData.cameras) {
  86789. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  86790. }
  86791. if (parsedData.nodes) {
  86792. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  86793. }
  86794. if (parsedData.images) {
  86795. parseObject(parsedData.images, "images", gltfRuntime);
  86796. }
  86797. if (parsedData.textures) {
  86798. parseObject(parsedData.textures, "textures", gltfRuntime);
  86799. }
  86800. if (parsedData.shaders) {
  86801. parseShaders(parsedData.shaders, gltfRuntime);
  86802. }
  86803. if (parsedData.programs) {
  86804. parseObject(parsedData.programs, "programs", gltfRuntime);
  86805. }
  86806. if (parsedData.samplers) {
  86807. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  86808. }
  86809. if (parsedData.techniques) {
  86810. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  86811. }
  86812. if (parsedData.materials) {
  86813. parseObject(parsedData.materials, "materials", gltfRuntime);
  86814. }
  86815. if (parsedData.animations) {
  86816. parseObject(parsedData.animations, "animations", gltfRuntime);
  86817. }
  86818. if (parsedData.skins) {
  86819. parseObject(parsedData.skins, "skins", gltfRuntime);
  86820. }
  86821. if (parsedData.scenes) {
  86822. gltfRuntime.scenes = parsedData.scenes;
  86823. }
  86824. if (parsedData.scene && parsedData.scenes) {
  86825. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  86826. }
  86827. return gltfRuntime;
  86828. };
  86829. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86830. var buffer = gltfRuntime.buffers[id];
  86831. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  86832. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  86833. }
  86834. else {
  86835. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  86836. if (request) {
  86837. onError(request.status + " " + request.statusText);
  86838. }
  86839. });
  86840. }
  86841. };
  86842. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86843. var texture = gltfRuntime.textures[id];
  86844. if (!texture || !texture.source) {
  86845. onError("");
  86846. return;
  86847. }
  86848. if (texture.babylonTexture) {
  86849. onSuccess(null);
  86850. return;
  86851. }
  86852. var source = gltfRuntime.images[texture.source];
  86853. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  86854. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  86855. }
  86856. else {
  86857. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  86858. if (request) {
  86859. onError(request.status + " " + request.statusText);
  86860. }
  86861. });
  86862. }
  86863. };
  86864. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86865. var texture = gltfRuntime.textures[id];
  86866. if (texture.babylonTexture) {
  86867. onSuccess(texture.babylonTexture);
  86868. return;
  86869. }
  86870. var sampler = gltfRuntime.samplers[texture.sampler];
  86871. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  86872. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  86873. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  86874. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  86875. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  86876. var blob = new Blob([buffer]);
  86877. var blobURL = URL.createObjectURL(blob);
  86878. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  86879. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  86880. if (sampler.wrapS !== undefined) {
  86881. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  86882. }
  86883. if (sampler.wrapT !== undefined) {
  86884. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  86885. }
  86886. newTexture.name = id;
  86887. texture.babylonTexture = newTexture;
  86888. onSuccess(newTexture);
  86889. };
  86890. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86891. var shader = gltfRuntime.shaders[id];
  86892. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  86893. var shaderString = atob(shader.uri.split(",")[1]);
  86894. onSuccess(shaderString);
  86895. }
  86896. else {
  86897. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  86898. if (request) {
  86899. onError(request.status + " " + request.statusText);
  86900. }
  86901. });
  86902. }
  86903. };
  86904. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86905. var material = gltfRuntime.materials[id];
  86906. if (!material.technique) {
  86907. if (onError) {
  86908. onError("No technique found.");
  86909. }
  86910. return;
  86911. }
  86912. var technique = gltfRuntime.techniques[material.technique];
  86913. if (!technique) {
  86914. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86915. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  86916. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86917. onSuccess(defaultMaterial);
  86918. return;
  86919. }
  86920. var program = gltfRuntime.programs[technique.program];
  86921. var states = technique.states;
  86922. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  86923. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  86924. var newVertexShader = "";
  86925. var newPixelShader = "";
  86926. var vertexTokenizer = new Tokenizer(vertexShader);
  86927. var pixelTokenizer = new Tokenizer(pixelShader);
  86928. var unTreatedUniforms = {};
  86929. var uniforms = [];
  86930. var attributes = [];
  86931. var samplers = [];
  86932. // Fill uniform, sampler2D and attributes
  86933. for (var unif in technique.uniforms) {
  86934. var uniform = technique.uniforms[unif];
  86935. var uniformParameter = technique.parameters[uniform];
  86936. unTreatedUniforms[unif] = uniformParameter;
  86937. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  86938. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  86939. if (transformIndex !== -1) {
  86940. uniforms.push(babylonTransforms[transformIndex]);
  86941. delete unTreatedUniforms[unif];
  86942. }
  86943. else {
  86944. uniforms.push(unif);
  86945. }
  86946. }
  86947. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  86948. samplers.push(unif);
  86949. }
  86950. else {
  86951. uniforms.push(unif);
  86952. }
  86953. }
  86954. for (var attr in technique.attributes) {
  86955. var attribute = technique.attributes[attr];
  86956. var attributeParameter = technique.parameters[attribute];
  86957. if (attributeParameter.semantic) {
  86958. attributes.push(getAttribute(attributeParameter));
  86959. }
  86960. }
  86961. // Configure vertex shader
  86962. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  86963. var tokenType = vertexTokenizer.currentToken;
  86964. if (tokenType !== ETokenType.IDENTIFIER) {
  86965. newVertexShader += vertexTokenizer.currentString;
  86966. continue;
  86967. }
  86968. var foundAttribute = false;
  86969. for (var attr in technique.attributes) {
  86970. var attribute = technique.attributes[attr];
  86971. var attributeParameter = technique.parameters[attribute];
  86972. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  86973. newVertexShader += getAttribute(attributeParameter);
  86974. foundAttribute = true;
  86975. break;
  86976. }
  86977. }
  86978. if (foundAttribute) {
  86979. continue;
  86980. }
  86981. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  86982. }
  86983. // Configure pixel shader
  86984. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  86985. var tokenType = pixelTokenizer.currentToken;
  86986. if (tokenType !== ETokenType.IDENTIFIER) {
  86987. newPixelShader += pixelTokenizer.currentString;
  86988. continue;
  86989. }
  86990. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  86991. }
  86992. // Create shader material
  86993. var shaderPath = {
  86994. vertex: program.vertexShader + id,
  86995. fragment: program.fragmentShader + id
  86996. };
  86997. var options = {
  86998. attributes: attributes,
  86999. uniforms: uniforms,
  87000. samplers: samplers,
  87001. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  87002. };
  87003. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  87004. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  87005. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  87006. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  87007. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  87008. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87009. if (states && states.functions) {
  87010. var functions = states.functions;
  87011. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  87012. shaderMaterial.backFaceCulling = false;
  87013. }
  87014. var blendFunc = functions.blendFuncSeparate;
  87015. if (blendFunc) {
  87016. 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) {
  87017. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  87018. }
  87019. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87020. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87021. }
  87022. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87023. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  87024. }
  87025. 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) {
  87026. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  87027. }
  87028. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87029. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  87030. }
  87031. 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) {
  87032. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  87033. }
  87034. }
  87035. }
  87036. };
  87037. return GLTFLoaderBase;
  87038. }());
  87039. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  87040. /**
  87041. * glTF V1 Loader
  87042. */
  87043. var GLTFLoader = /** @class */ (function () {
  87044. function GLTFLoader() {
  87045. // #region Stubs for IGLTFLoader interface
  87046. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87047. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87048. this.compileMaterials = false;
  87049. this.useClipPlane = false;
  87050. this.compileShadowGenerators = false;
  87051. this.onDisposeObservable = new BABYLON.Observable();
  87052. this.onMeshLoadedObservable = new BABYLON.Observable();
  87053. this.onTextureLoadedObservable = new BABYLON.Observable();
  87054. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87055. this.onCompleteObservable = new BABYLON.Observable();
  87056. }
  87057. GLTFLoader.RegisterExtension = function (extension) {
  87058. if (GLTFLoader.Extensions[extension.name]) {
  87059. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  87060. return;
  87061. }
  87062. GLTFLoader.Extensions[extension.name] = extension;
  87063. };
  87064. GLTFLoader.prototype.dispose = function () { };
  87065. // #endregion
  87066. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87067. var _this = this;
  87068. scene.useRightHandedSystem = true;
  87069. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87070. gltfRuntime.importOnlyMeshes = true;
  87071. if (meshesNames === "") {
  87072. gltfRuntime.importMeshesNames = [];
  87073. }
  87074. else if (typeof meshesNames === "string") {
  87075. gltfRuntime.importMeshesNames = [meshesNames];
  87076. }
  87077. else if (meshesNames && !(meshesNames instanceof Array)) {
  87078. gltfRuntime.importMeshesNames = [meshesNames];
  87079. }
  87080. else {
  87081. gltfRuntime.importMeshesNames = [];
  87082. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  87083. }
  87084. // Create nodes
  87085. _this._createNodes(gltfRuntime);
  87086. var meshes = new Array();
  87087. var skeletons = new Array();
  87088. // Fill arrays of meshes and skeletons
  87089. for (var nde in gltfRuntime.nodes) {
  87090. var node = gltfRuntime.nodes[nde];
  87091. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  87092. meshes.push(node.babylonNode);
  87093. }
  87094. }
  87095. for (var skl in gltfRuntime.skins) {
  87096. var skin = gltfRuntime.skins[skl];
  87097. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  87098. skeletons.push(skin.babylonSkeleton);
  87099. }
  87100. }
  87101. // Load buffers, shaders, materials, etc.
  87102. _this._loadBuffersAsync(gltfRuntime, function () {
  87103. _this._loadShadersAsync(gltfRuntime, function () {
  87104. importMaterials(gltfRuntime);
  87105. postLoad(gltfRuntime);
  87106. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87107. onSuccess(meshes, [], skeletons);
  87108. }
  87109. });
  87110. }, onProgress);
  87111. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87112. onSuccess(meshes, [], skeletons);
  87113. }
  87114. }, onError);
  87115. return true;
  87116. };
  87117. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87118. var _this = this;
  87119. scene.useRightHandedSystem = true;
  87120. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87121. // Load runtime extensios
  87122. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  87123. // Create nodes
  87124. _this._createNodes(gltfRuntime);
  87125. // Load buffers, shaders, materials, etc.
  87126. _this._loadBuffersAsync(gltfRuntime, function () {
  87127. _this._loadShadersAsync(gltfRuntime, function () {
  87128. importMaterials(gltfRuntime);
  87129. postLoad(gltfRuntime);
  87130. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  87131. onSuccess();
  87132. }
  87133. });
  87134. });
  87135. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  87136. onSuccess();
  87137. }
  87138. }, onError);
  87139. }, onError);
  87140. };
  87141. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  87142. var hasShaders = false;
  87143. var processShader = function (sha, shader) {
  87144. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  87145. gltfRuntime.loadedShaderCount++;
  87146. if (shaderString) {
  87147. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  87148. }
  87149. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  87150. onload();
  87151. }
  87152. }, function () {
  87153. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  87154. });
  87155. };
  87156. for (var sha in gltfRuntime.shaders) {
  87157. hasShaders = true;
  87158. var shader = gltfRuntime.shaders[sha];
  87159. if (shader) {
  87160. processShader.bind(this, sha, shader)();
  87161. }
  87162. else {
  87163. BABYLON.Tools.Error("No shader named: " + sha);
  87164. }
  87165. }
  87166. if (!hasShaders) {
  87167. onload();
  87168. }
  87169. };
  87170. ;
  87171. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  87172. var hasBuffers = false;
  87173. var processBuffer = function (buf, buffer) {
  87174. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  87175. gltfRuntime.loadedBufferCount++;
  87176. if (bufferView) {
  87177. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  87178. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  87179. }
  87180. gltfRuntime.loadedBufferViews[buf] = bufferView;
  87181. }
  87182. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  87183. onLoad();
  87184. }
  87185. }, function () {
  87186. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  87187. });
  87188. };
  87189. for (var buf in gltfRuntime.buffers) {
  87190. hasBuffers = true;
  87191. var buffer = gltfRuntime.buffers[buf];
  87192. if (buffer) {
  87193. processBuffer.bind(this, buf, buffer)();
  87194. }
  87195. else {
  87196. BABYLON.Tools.Error("No buffer named: " + buf);
  87197. }
  87198. }
  87199. if (!hasBuffers) {
  87200. onLoad();
  87201. }
  87202. };
  87203. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  87204. var currentScene = gltfRuntime.currentScene;
  87205. if (currentScene) {
  87206. // Only one scene even if multiple scenes are defined
  87207. for (var i = 0; i < currentScene.nodes.length; i++) {
  87208. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87209. }
  87210. }
  87211. else {
  87212. // Load all scenes
  87213. for (var thing in gltfRuntime.scenes) {
  87214. currentScene = gltfRuntime.scenes[thing];
  87215. for (var i = 0; i < currentScene.nodes.length; i++) {
  87216. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87217. }
  87218. }
  87219. }
  87220. };
  87221. GLTFLoader.Extensions = {};
  87222. return GLTFLoader;
  87223. }());
  87224. GLTF1.GLTFLoader = GLTFLoader;
  87225. ;
  87226. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  87227. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87228. })(BABYLON || (BABYLON = {}));
  87229. //# sourceMappingURL=babylon.glTFLoader.js.map
  87230. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87231. var BABYLON;
  87232. (function (BABYLON) {
  87233. var GLTF1;
  87234. (function (GLTF1) {
  87235. /**
  87236. * Utils functions for GLTF
  87237. */
  87238. var GLTFUtils = /** @class */ (function () {
  87239. function GLTFUtils() {
  87240. }
  87241. /**
  87242. * Sets the given "parameter" matrix
  87243. * @param scene: the {BABYLON.Scene} object
  87244. * @param source: the source node where to pick the matrix
  87245. * @param parameter: the GLTF technique parameter
  87246. * @param uniformName: the name of the shader's uniform
  87247. * @param shaderMaterial: the shader material
  87248. */
  87249. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  87250. var mat = null;
  87251. if (parameter.semantic === "MODEL") {
  87252. mat = source.getWorldMatrix();
  87253. }
  87254. else if (parameter.semantic === "PROJECTION") {
  87255. mat = scene.getProjectionMatrix();
  87256. }
  87257. else if (parameter.semantic === "VIEW") {
  87258. mat = scene.getViewMatrix();
  87259. }
  87260. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  87261. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  87262. }
  87263. else if (parameter.semantic === "MODELVIEW") {
  87264. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  87265. }
  87266. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  87267. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  87268. }
  87269. else if (parameter.semantic === "MODELINVERSE") {
  87270. mat = source.getWorldMatrix().invert();
  87271. }
  87272. else if (parameter.semantic === "VIEWINVERSE") {
  87273. mat = scene.getViewMatrix().invert();
  87274. }
  87275. else if (parameter.semantic === "PROJECTIONINVERSE") {
  87276. mat = scene.getProjectionMatrix().invert();
  87277. }
  87278. else if (parameter.semantic === "MODELVIEWINVERSE") {
  87279. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  87280. }
  87281. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  87282. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  87283. }
  87284. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  87285. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  87286. }
  87287. else {
  87288. debugger;
  87289. }
  87290. if (mat) {
  87291. switch (parameter.type) {
  87292. case GLTF1.EParameterType.FLOAT_MAT2:
  87293. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  87294. break;
  87295. case GLTF1.EParameterType.FLOAT_MAT3:
  87296. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  87297. break;
  87298. case GLTF1.EParameterType.FLOAT_MAT4:
  87299. shaderMaterial.setMatrix(uniformName, mat);
  87300. break;
  87301. default: break;
  87302. }
  87303. }
  87304. };
  87305. /**
  87306. * Sets the given "parameter" matrix
  87307. * @param shaderMaterial: the shader material
  87308. * @param uniform: the name of the shader's uniform
  87309. * @param value: the value of the uniform
  87310. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  87311. */
  87312. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  87313. switch (type) {
  87314. case GLTF1.EParameterType.FLOAT:
  87315. shaderMaterial.setFloat(uniform, value);
  87316. return true;
  87317. case GLTF1.EParameterType.FLOAT_VEC2:
  87318. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  87319. return true;
  87320. case GLTF1.EParameterType.FLOAT_VEC3:
  87321. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  87322. return true;
  87323. case GLTF1.EParameterType.FLOAT_VEC4:
  87324. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  87325. return true;
  87326. default: return false;
  87327. }
  87328. };
  87329. /**
  87330. * If the uri is a base64 string
  87331. * @param uri: the uri to test
  87332. */
  87333. GLTFUtils.IsBase64 = function (uri) {
  87334. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  87335. };
  87336. /**
  87337. * Decode the base64 uri
  87338. * @param uri: the uri to decode
  87339. */
  87340. GLTFUtils.DecodeBase64 = function (uri) {
  87341. var decodedString = atob(uri.split(",")[1]);
  87342. var bufferLength = decodedString.length;
  87343. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  87344. for (var i = 0; i < bufferLength; i++) {
  87345. bufferView[i] = decodedString.charCodeAt(i);
  87346. }
  87347. return bufferView.buffer;
  87348. };
  87349. /**
  87350. * Returns the wrap mode of the texture
  87351. * @param mode: the mode value
  87352. */
  87353. GLTFUtils.GetWrapMode = function (mode) {
  87354. switch (mode) {
  87355. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  87356. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  87357. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87358. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87359. }
  87360. };
  87361. /**
  87362. * Returns the byte stride giving an accessor
  87363. * @param accessor: the GLTF accessor objet
  87364. */
  87365. GLTFUtils.GetByteStrideFromType = function (accessor) {
  87366. // Needs this function since "byteStride" isn't requiered in glTF format
  87367. var type = accessor.type;
  87368. switch (type) {
  87369. case "VEC2": return 2;
  87370. case "VEC3": return 3;
  87371. case "VEC4": return 4;
  87372. case "MAT2": return 4;
  87373. case "MAT3": return 9;
  87374. case "MAT4": return 16;
  87375. default: return 1;
  87376. }
  87377. };
  87378. /**
  87379. * Returns the texture filter mode giving a mode value
  87380. * @param mode: the filter mode value
  87381. */
  87382. GLTFUtils.GetTextureFilterMode = function (mode) {
  87383. switch (mode) {
  87384. case GLTF1.ETextureFilterType.LINEAR:
  87385. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  87386. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87387. case GLTF1.ETextureFilterType.NEAREST:
  87388. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  87389. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  87390. }
  87391. };
  87392. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  87393. var byteOffset = bufferView.byteOffset + byteOffset;
  87394. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  87395. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  87396. throw new Error("Buffer access is out of range");
  87397. }
  87398. var buffer = loadedBufferView.buffer;
  87399. byteOffset += loadedBufferView.byteOffset;
  87400. switch (componentType) {
  87401. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  87402. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  87403. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  87404. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  87405. default: return new Float32Array(buffer, byteOffset, byteLength);
  87406. }
  87407. };
  87408. /**
  87409. * Returns a buffer from its accessor
  87410. * @param gltfRuntime: the GLTF runtime
  87411. * @param accessor: the GLTF accessor
  87412. */
  87413. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  87414. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  87415. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  87416. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  87417. };
  87418. /**
  87419. * Decodes a buffer view into a string
  87420. * @param view: the buffer view
  87421. */
  87422. GLTFUtils.DecodeBufferToText = function (view) {
  87423. var result = "";
  87424. var length = view.byteLength;
  87425. for (var i = 0; i < length; ++i) {
  87426. result += String.fromCharCode(view[i]);
  87427. }
  87428. return result;
  87429. };
  87430. /**
  87431. * Returns the default material of gltf. Related to
  87432. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  87433. * @param scene: the Babylon.js scene
  87434. */
  87435. GLTFUtils.GetDefaultMaterial = function (scene) {
  87436. if (!GLTFUtils._DefaultMaterial) {
  87437. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  87438. "precision highp float;",
  87439. "",
  87440. "uniform mat4 worldView;",
  87441. "uniform mat4 projection;",
  87442. "",
  87443. "attribute vec3 position;",
  87444. "",
  87445. "void main(void)",
  87446. "{",
  87447. " gl_Position = projection * worldView * vec4(position, 1.0);",
  87448. "}"
  87449. ].join("\n");
  87450. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  87451. "precision highp float;",
  87452. "",
  87453. "uniform vec4 u_emission;",
  87454. "",
  87455. "void main(void)",
  87456. "{",
  87457. " gl_FragColor = u_emission;",
  87458. "}"
  87459. ].join("\n");
  87460. var shaderPath = {
  87461. vertex: "GLTFDefaultMaterial",
  87462. fragment: "GLTFDefaultMaterial"
  87463. };
  87464. var options = {
  87465. attributes: ["position"],
  87466. uniforms: ["worldView", "projection", "u_emission"],
  87467. samplers: new Array(),
  87468. needAlphaBlending: false
  87469. };
  87470. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  87471. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  87472. }
  87473. return GLTFUtils._DefaultMaterial;
  87474. };
  87475. // The GLTF default material
  87476. GLTFUtils._DefaultMaterial = null;
  87477. return GLTFUtils;
  87478. }());
  87479. GLTF1.GLTFUtils = GLTFUtils;
  87480. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87481. })(BABYLON || (BABYLON = {}));
  87482. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  87483. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87484. var BABYLON;
  87485. (function (BABYLON) {
  87486. var GLTF1;
  87487. (function (GLTF1) {
  87488. var GLTFLoaderExtension = /** @class */ (function () {
  87489. function GLTFLoaderExtension(name) {
  87490. this._name = name;
  87491. }
  87492. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  87493. get: function () {
  87494. return this._name;
  87495. },
  87496. enumerable: true,
  87497. configurable: true
  87498. });
  87499. /**
  87500. * Defines an override for loading the runtime
  87501. * Return true to stop further extensions from loading the runtime
  87502. */
  87503. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87504. return false;
  87505. };
  87506. /**
  87507. * Defines an onverride for creating gltf runtime
  87508. * Return true to stop further extensions from creating the runtime
  87509. */
  87510. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87511. return false;
  87512. };
  87513. /**
  87514. * Defines an override for loading buffers
  87515. * Return true to stop further extensions from loading this buffer
  87516. */
  87517. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87518. return false;
  87519. };
  87520. /**
  87521. * Defines an override for loading texture buffers
  87522. * Return true to stop further extensions from loading this texture data
  87523. */
  87524. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87525. return false;
  87526. };
  87527. /**
  87528. * Defines an override for creating textures
  87529. * Return true to stop further extensions from loading this texture
  87530. */
  87531. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87532. return false;
  87533. };
  87534. /**
  87535. * Defines an override for loading shader strings
  87536. * Return true to stop further extensions from loading this shader data
  87537. */
  87538. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87539. return false;
  87540. };
  87541. /**
  87542. * Defines an override for loading materials
  87543. * Return true to stop further extensions from loading this material
  87544. */
  87545. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87546. return false;
  87547. };
  87548. // ---------
  87549. // Utilities
  87550. // ---------
  87551. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87552. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87553. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  87554. }, function () {
  87555. setTimeout(function () {
  87556. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87557. });
  87558. });
  87559. };
  87560. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87561. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87562. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  87563. }, function () {
  87564. setTimeout(function () {
  87565. onSuccess();
  87566. });
  87567. });
  87568. };
  87569. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87570. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87571. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87572. }, function () {
  87573. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87574. });
  87575. };
  87576. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  87577. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  87578. };
  87579. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87580. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87581. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87582. }, function () {
  87583. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87584. });
  87585. };
  87586. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87587. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87588. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87589. }, function () {
  87590. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87591. });
  87592. };
  87593. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87594. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87595. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  87596. }, function () {
  87597. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  87598. });
  87599. };
  87600. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87601. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87602. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  87603. }, function () {
  87604. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  87605. });
  87606. };
  87607. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  87608. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  87609. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  87610. if (func(loaderExtension)) {
  87611. return;
  87612. }
  87613. }
  87614. defaultFunc();
  87615. };
  87616. return GLTFLoaderExtension;
  87617. }());
  87618. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  87619. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87620. })(BABYLON || (BABYLON = {}));
  87621. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  87622. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87623. var BABYLON;
  87624. (function (BABYLON) {
  87625. var GLTF1;
  87626. (function (GLTF1) {
  87627. var BinaryExtensionBufferName = "binary_glTF";
  87628. ;
  87629. ;
  87630. var GLTFBinaryExtension = /** @class */ (function (_super) {
  87631. __extends(GLTFBinaryExtension, _super);
  87632. function GLTFBinaryExtension() {
  87633. return _super.call(this, "KHR_binary_glTF") || this;
  87634. }
  87635. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87636. var extensionsUsed = data.json.extensionsUsed;
  87637. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  87638. return false;
  87639. }
  87640. this._bin = data.bin;
  87641. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87642. return true;
  87643. };
  87644. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87645. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  87646. return false;
  87647. }
  87648. if (id !== BinaryExtensionBufferName) {
  87649. return false;
  87650. }
  87651. onSuccess(this._bin);
  87652. return true;
  87653. };
  87654. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87655. var texture = gltfRuntime.textures[id];
  87656. var source = gltfRuntime.images[texture.source];
  87657. if (!source.extensions || !(this.name in source.extensions)) {
  87658. return false;
  87659. }
  87660. var sourceExt = source.extensions[this.name];
  87661. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  87662. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  87663. onSuccess(buffer);
  87664. return true;
  87665. };
  87666. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87667. var shader = gltfRuntime.shaders[id];
  87668. if (!shader.extensions || !(this.name in shader.extensions)) {
  87669. return false;
  87670. }
  87671. var binaryExtensionShader = shader.extensions[this.name];
  87672. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  87673. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  87674. setTimeout(function () {
  87675. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  87676. onSuccess(shaderString);
  87677. });
  87678. return true;
  87679. };
  87680. return GLTFBinaryExtension;
  87681. }(GLTF1.GLTFLoaderExtension));
  87682. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  87683. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  87684. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87685. })(BABYLON || (BABYLON = {}));
  87686. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  87687. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87688. var BABYLON;
  87689. (function (BABYLON) {
  87690. var GLTF1;
  87691. (function (GLTF1) {
  87692. ;
  87693. ;
  87694. ;
  87695. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  87696. __extends(GLTFMaterialsCommonExtension, _super);
  87697. function GLTFMaterialsCommonExtension() {
  87698. return _super.call(this, "KHR_materials_common") || this;
  87699. }
  87700. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87701. if (!gltfRuntime.extensions)
  87702. return false;
  87703. var extension = gltfRuntime.extensions[this.name];
  87704. if (!extension)
  87705. return false;
  87706. // Create lights
  87707. var lights = extension.lights;
  87708. if (lights) {
  87709. for (var thing in lights) {
  87710. var light = lights[thing];
  87711. switch (light.type) {
  87712. case "ambient":
  87713. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  87714. var ambient = light.ambient;
  87715. if (ambient) {
  87716. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  87717. }
  87718. break;
  87719. case "point":
  87720. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  87721. var point = light.point;
  87722. if (point) {
  87723. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  87724. }
  87725. break;
  87726. case "directional":
  87727. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  87728. var directional = light.directional;
  87729. if (directional) {
  87730. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  87731. }
  87732. break;
  87733. case "spot":
  87734. var spot = light.spot;
  87735. if (spot) {
  87736. 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);
  87737. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  87738. }
  87739. break;
  87740. default:
  87741. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  87742. break;
  87743. }
  87744. }
  87745. }
  87746. return false;
  87747. };
  87748. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87749. var material = gltfRuntime.materials[id];
  87750. if (!material || !material.extensions)
  87751. return false;
  87752. var extension = material.extensions[this.name];
  87753. if (!extension)
  87754. return false;
  87755. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  87756. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87757. if (extension.technique === "CONSTANT") {
  87758. standardMaterial.disableLighting = true;
  87759. }
  87760. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  87761. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  87762. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  87763. // Ambient
  87764. if (typeof extension.values.ambient === "string") {
  87765. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  87766. }
  87767. else {
  87768. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  87769. }
  87770. // Diffuse
  87771. if (typeof extension.values.diffuse === "string") {
  87772. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  87773. }
  87774. else {
  87775. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  87776. }
  87777. // Emission
  87778. if (typeof extension.values.emission === "string") {
  87779. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  87780. }
  87781. else {
  87782. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  87783. }
  87784. // Specular
  87785. if (typeof extension.values.specular === "string") {
  87786. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  87787. }
  87788. else {
  87789. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  87790. }
  87791. return true;
  87792. };
  87793. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  87794. // Create buffer from texture url
  87795. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  87796. // Create texture from buffer
  87797. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  87798. }, onError);
  87799. };
  87800. return GLTFMaterialsCommonExtension;
  87801. }(GLTF1.GLTFLoaderExtension));
  87802. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  87803. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  87804. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87805. })(BABYLON || (BABYLON = {}));
  87806. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  87807. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87808. var BABYLON;
  87809. (function (BABYLON) {
  87810. var GLTF2;
  87811. (function (GLTF2) {
  87812. /**
  87813. * Enums
  87814. */
  87815. var EComponentType;
  87816. (function (EComponentType) {
  87817. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  87818. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  87819. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  87820. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  87821. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  87822. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  87823. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  87824. var EMeshPrimitiveMode;
  87825. (function (EMeshPrimitiveMode) {
  87826. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  87827. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  87828. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  87829. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  87830. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  87831. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  87832. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  87833. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  87834. var ETextureMagFilter;
  87835. (function (ETextureMagFilter) {
  87836. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  87837. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  87838. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  87839. var ETextureMinFilter;
  87840. (function (ETextureMinFilter) {
  87841. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  87842. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  87843. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  87844. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  87845. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  87846. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  87847. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  87848. var ETextureWrapMode;
  87849. (function (ETextureWrapMode) {
  87850. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  87851. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  87852. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  87853. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  87854. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  87855. })(BABYLON || (BABYLON = {}));
  87856. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  87857. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87858. var BABYLON;
  87859. (function (BABYLON) {
  87860. var GLTF2;
  87861. (function (GLTF2) {
  87862. var GLTFLoaderTracker = /** @class */ (function () {
  87863. function GLTFLoaderTracker(onComplete) {
  87864. this._pendingCount = 0;
  87865. this._callback = onComplete;
  87866. }
  87867. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  87868. this._pendingCount++;
  87869. };
  87870. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  87871. if (--this._pendingCount === 0) {
  87872. this._callback();
  87873. }
  87874. };
  87875. return GLTFLoaderTracker;
  87876. }());
  87877. var GLTFLoader = /** @class */ (function () {
  87878. function GLTFLoader() {
  87879. this._disposed = false;
  87880. this._defaultSampler = {};
  87881. this._renderReady = false;
  87882. this._requests = new Array();
  87883. this._renderReadyObservable = new BABYLON.Observable();
  87884. // Count of pending work that needs to complete before the asset is rendered.
  87885. this._renderPendingCount = 0;
  87886. // Count of pending work that needs to complete before the loader is disposed.
  87887. this._loaderPendingCount = 0;
  87888. this._loaderTrackers = new Array();
  87889. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87890. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87891. this.compileMaterials = false;
  87892. this.useClipPlane = false;
  87893. this.compileShadowGenerators = false;
  87894. this.onDisposeObservable = new BABYLON.Observable();
  87895. this.onMeshLoadedObservable = new BABYLON.Observable();
  87896. this.onTextureLoadedObservable = new BABYLON.Observable();
  87897. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87898. this.onCompleteObservable = new BABYLON.Observable();
  87899. }
  87900. GLTFLoader.RegisterExtension = function (extension) {
  87901. if (GLTFLoader.Extensions[extension.name]) {
  87902. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  87903. return;
  87904. }
  87905. GLTFLoader.Extensions[extension.name] = extension;
  87906. // Keep the order of registration so that extensions registered first are called first.
  87907. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  87908. };
  87909. GLTFLoader.prototype.dispose = function () {
  87910. if (this._disposed) {
  87911. return;
  87912. }
  87913. this._disposed = true;
  87914. this._abortRequests();
  87915. this._releaseResources();
  87916. this.onDisposeObservable.notifyObservers(this);
  87917. };
  87918. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87919. var _this = this;
  87920. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  87921. if (onSuccess) {
  87922. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  87923. }
  87924. }, onProgress, onError);
  87925. };
  87926. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87927. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  87928. };
  87929. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87930. var _this = this;
  87931. this._babylonScene = scene;
  87932. this._rootUrl = rootUrl;
  87933. this._successCallback = onSuccess;
  87934. this._progressCallback = onProgress;
  87935. this._errorCallback = onError;
  87936. this._tryCatchOnError(function () {
  87937. _this._loadData(data);
  87938. _this._addPendingData(_this);
  87939. _this._loadDefaultScene(nodeNames);
  87940. _this._loadAnimations();
  87941. _this._removePendingData(_this);
  87942. });
  87943. };
  87944. GLTFLoader.prototype._onProgress = function () {
  87945. if (!this._progressCallback) {
  87946. return;
  87947. }
  87948. var lengthComputable = true;
  87949. var loaded = 0;
  87950. var total = 0;
  87951. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  87952. var request = _a[_i];
  87953. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  87954. return;
  87955. }
  87956. lengthComputable = lengthComputable && request._lengthComputable;
  87957. loaded += request._loaded;
  87958. total += request._total;
  87959. }
  87960. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  87961. };
  87962. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  87963. if (this._renderReady) {
  87964. func();
  87965. }
  87966. else {
  87967. this._renderReadyObservable.add(func);
  87968. }
  87969. };
  87970. GLTFLoader.prototype._onRenderReady = function () {
  87971. this._rootNode.babylonMesh.setEnabled(true);
  87972. this._startAnimations();
  87973. if (this._successCallback) {
  87974. this._successCallback();
  87975. }
  87976. this._renderReadyObservable.notifyObservers(this);
  87977. };
  87978. GLTFLoader.prototype._onComplete = function () {
  87979. this._abortRequests();
  87980. this._releaseResources();
  87981. this.onCompleteObservable.notifyObservers(this);
  87982. };
  87983. GLTFLoader.prototype._loadData = function (data) {
  87984. this._gltf = data.json;
  87985. // Assign the index of each object for convinience.
  87986. GLTFLoader._AssignIndices(this._gltf.accessors);
  87987. GLTFLoader._AssignIndices(this._gltf.animations);
  87988. GLTFLoader._AssignIndices(this._gltf.buffers);
  87989. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  87990. GLTFLoader._AssignIndices(this._gltf.images);
  87991. GLTFLoader._AssignIndices(this._gltf.materials);
  87992. GLTFLoader._AssignIndices(this._gltf.meshes);
  87993. GLTFLoader._AssignIndices(this._gltf.nodes);
  87994. GLTFLoader._AssignIndices(this._gltf.samplers);
  87995. GLTFLoader._AssignIndices(this._gltf.scenes);
  87996. GLTFLoader._AssignIndices(this._gltf.skins);
  87997. GLTFLoader._AssignIndices(this._gltf.textures);
  87998. // Handle global extensions as they may add their own data types.
  87999. GLTF2.GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  88000. if (data.bin) {
  88001. var buffers = this._gltf.buffers;
  88002. if (buffers && buffers[0] && !buffers[0].uri) {
  88003. var binaryBuffer = buffers[0];
  88004. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  88005. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  88006. }
  88007. binaryBuffer.loadedData = data.bin;
  88008. }
  88009. else {
  88010. BABYLON.Tools.Warn("Unexpected BIN chunk");
  88011. }
  88012. }
  88013. };
  88014. GLTFLoader.prototype._getMeshes = function () {
  88015. var meshes = new Array();
  88016. // Root mesh is always first.
  88017. meshes.push(this._rootNode.babylonMesh);
  88018. var nodes = this._gltf.nodes;
  88019. if (nodes) {
  88020. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  88021. var node = nodes_1[_i];
  88022. if (node.babylonMesh) {
  88023. meshes.push(node.babylonMesh);
  88024. }
  88025. }
  88026. }
  88027. return meshes;
  88028. };
  88029. GLTFLoader.prototype._getSkeletons = function () {
  88030. var skeletons = new Array();
  88031. var skins = this._gltf.skins;
  88032. if (skins) {
  88033. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  88034. var skin = skins_1[_i];
  88035. if (skin.babylonSkeleton) {
  88036. skeletons.push(skin.babylonSkeleton);
  88037. }
  88038. }
  88039. }
  88040. return skeletons;
  88041. };
  88042. GLTFLoader.prototype._startAnimations = function () {
  88043. var animations = this._gltf.animations;
  88044. if (!animations) {
  88045. return;
  88046. }
  88047. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  88048. var animation = animations_1[_i];
  88049. animation.babylonAnimationGroup.normalize();
  88050. }
  88051. switch (this.animationStartMode) {
  88052. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  88053. // do nothing
  88054. break;
  88055. }
  88056. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  88057. var animation = animations[0];
  88058. animation.babylonAnimationGroup.start(true);
  88059. break;
  88060. }
  88061. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  88062. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  88063. var animation = animations_2[_a];
  88064. animation.babylonAnimationGroup.start(true);
  88065. }
  88066. break;
  88067. }
  88068. default: {
  88069. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  88070. return;
  88071. }
  88072. }
  88073. };
  88074. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  88075. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  88076. if (!scene) {
  88077. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  88078. }
  88079. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  88080. };
  88081. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  88082. var _this = this;
  88083. GLTF2.GLTFLoaderExtension.LoadScene(this, context, scene);
  88084. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  88085. switch (this.coordinateSystemMode) {
  88086. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  88087. if (!this._babylonScene.useRightHandedSystem) {
  88088. this._rootNode.rotation = [0, 1, 0, 0];
  88089. this._rootNode.scale = [1, 1, -1];
  88090. this._loadTransform(this._rootNode);
  88091. }
  88092. break;
  88093. }
  88094. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  88095. this._babylonScene.useRightHandedSystem = true;
  88096. break;
  88097. }
  88098. default: {
  88099. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  88100. return;
  88101. }
  88102. }
  88103. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  88104. var nodeIndices = scene.nodes;
  88105. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  88106. node.parent = parentNode;
  88107. return true;
  88108. }, this._rootNode);
  88109. if (nodeNames) {
  88110. if (!(nodeNames instanceof Array)) {
  88111. nodeNames = [nodeNames];
  88112. }
  88113. var filteredNodeIndices_1 = new Array();
  88114. this._traverseNodes(context, nodeIndices, function (node) {
  88115. if (nodeNames.indexOf(node.name) !== -1) {
  88116. filteredNodeIndices_1.push(node.index);
  88117. node.parent = _this._rootNode;
  88118. return false;
  88119. }
  88120. return true;
  88121. }, this._rootNode);
  88122. nodeIndices = filteredNodeIndices_1;
  88123. }
  88124. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  88125. var index = nodeIndices_1[_i];
  88126. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88127. if (!node) {
  88128. throw new Error(context + ": Failed to find node " + index);
  88129. }
  88130. this._loadNode("#/nodes/" + index, node);
  88131. }
  88132. // Disable the root mesh until the asset is ready to render.
  88133. this._rootNode.babylonMesh.setEnabled(false);
  88134. };
  88135. GLTFLoader.prototype._loadNode = function (context, node) {
  88136. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  88137. return;
  88138. }
  88139. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  88140. this._loadTransform(node);
  88141. if (node.mesh != null) {
  88142. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  88143. if (!mesh) {
  88144. throw new Error(context + ": Failed to find mesh " + node.mesh);
  88145. }
  88146. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  88147. }
  88148. node.babylonMesh.parent = node.parent.babylonMesh;
  88149. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88150. node.babylonAnimationTargets.push(node.babylonMesh);
  88151. if (node.skin != null) {
  88152. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  88153. if (!skin_1) {
  88154. throw new Error(context + ": Failed to find skin " + node.skin);
  88155. }
  88156. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  88157. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  88158. node.babylonMesh._refreshBoundingInfo(true);
  88159. });
  88160. node.babylonMesh.parent = this._rootNode.babylonMesh;
  88161. node.babylonMesh.position = BABYLON.Vector3.Zero();
  88162. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88163. node.babylonMesh.scaling = BABYLON.Vector3.One();
  88164. }
  88165. if (node.camera != null) {
  88166. // TODO: handle cameras
  88167. }
  88168. if (node.children) {
  88169. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  88170. var index = _a[_i];
  88171. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88172. if (!childNode) {
  88173. throw new Error(context + ": Failed to find child node " + index);
  88174. }
  88175. this._loadNode("#/nodes/" + index, childNode);
  88176. }
  88177. }
  88178. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  88179. };
  88180. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  88181. var _this = this;
  88182. var primitives = mesh.primitives;
  88183. if (!primitives || primitives.length === 0) {
  88184. throw new Error(context + ": Primitives are missing");
  88185. }
  88186. this._createMorphTargets(context, node, mesh);
  88187. this._loadAllVertexDataAsync(context, mesh, function () {
  88188. _this._loadMorphTargets(context, node, mesh);
  88189. var vertexData = new BABYLON.VertexData();
  88190. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  88191. var primitive = primitives_1[_i];
  88192. vertexData.merge(primitive.vertexData);
  88193. }
  88194. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  88195. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  88196. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  88197. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  88198. node.babylonMesh.subMeshes = [];
  88199. var verticesStart = 0;
  88200. var indicesStart = 0;
  88201. for (var index = 0; index < primitives.length; index++) {
  88202. var vertexData_1 = primitives[index].vertexData;
  88203. var verticesCount = vertexData_1.positions.length;
  88204. var indicesCount = vertexData_1.indices.length;
  88205. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  88206. verticesStart += verticesCount;
  88207. indicesStart += indicesCount;
  88208. }
  88209. ;
  88210. });
  88211. if (primitives.length === 1) {
  88212. var primitive = primitives[0];
  88213. if (primitive.material == null) {
  88214. node.babylonMesh.material = this._getDefaultMaterial();
  88215. }
  88216. else {
  88217. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  88218. if (!material) {
  88219. throw new Error(context + ": Failed to find material " + primitive.material);
  88220. }
  88221. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88222. if (isNew) {
  88223. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88224. }
  88225. node.babylonMesh.material = babylonMaterial;
  88226. });
  88227. }
  88228. }
  88229. else {
  88230. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  88231. node.babylonMesh.material = multiMaterial;
  88232. var subMaterials_1 = multiMaterial.subMaterials;
  88233. var _loop_1 = function (index) {
  88234. var primitive = primitives[index];
  88235. if (primitive.material == null) {
  88236. subMaterials_1[index] = this_1._getDefaultMaterial();
  88237. }
  88238. else {
  88239. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  88240. if (!material) {
  88241. throw new Error(context + ": Failed to find material " + primitive.material);
  88242. }
  88243. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88244. if (isNew) {
  88245. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88246. }
  88247. subMaterials_1[index] = babylonMaterial;
  88248. });
  88249. }
  88250. };
  88251. var this_1 = this;
  88252. for (var index = 0; index < primitives.length; index++) {
  88253. _loop_1(index);
  88254. }
  88255. ;
  88256. }
  88257. };
  88258. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  88259. var primitives = mesh.primitives;
  88260. var numRemainingPrimitives = primitives.length;
  88261. var _loop_2 = function (index) {
  88262. var primitive = primitives[index];
  88263. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  88264. primitive.vertexData = vertexData;
  88265. if (--numRemainingPrimitives === 0) {
  88266. onSuccess();
  88267. }
  88268. });
  88269. };
  88270. var this_2 = this;
  88271. for (var index = 0; index < primitives.length; index++) {
  88272. _loop_2(index);
  88273. }
  88274. };
  88275. /**
  88276. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  88277. * @param {ArrayBufferView} data
  88278. * @param {IGLTFAccessor} accessor
  88279. */
  88280. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  88281. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  88282. return data;
  88283. }
  88284. var buffer = data;
  88285. var factor = 1;
  88286. switch (accessor.componentType) {
  88287. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88288. factor = 1 / 255;
  88289. break;
  88290. }
  88291. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88292. factor = 1 / 65535;
  88293. break;
  88294. }
  88295. default: {
  88296. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88297. }
  88298. }
  88299. var result = new Float32Array(accessor.count * 2);
  88300. for (var i = 0; i < result.length; ++i) {
  88301. result[i] = buffer[i] * factor;
  88302. }
  88303. return result;
  88304. };
  88305. /**
  88306. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  88307. * @param {ArrayBufferView} data
  88308. * @param {IGLTFAccessor} accessor
  88309. */
  88310. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  88311. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  88312. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  88313. return data;
  88314. }
  88315. var buffer = data;
  88316. var factor = 1;
  88317. switch (accessor.componentType) {
  88318. case GLTF2.EComponentType.FLOAT: {
  88319. factor = 1;
  88320. break;
  88321. }
  88322. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88323. factor = 1 / 255;
  88324. break;
  88325. }
  88326. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88327. factor = 1 / 65535;
  88328. break;
  88329. }
  88330. default: {
  88331. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88332. }
  88333. }
  88334. var result = new Float32Array(accessor.count * 4);
  88335. if (colorComponentCount === 4) {
  88336. for (var i = 0; i < result.length; ++i) {
  88337. result[i] = buffer[i] * factor;
  88338. }
  88339. }
  88340. else {
  88341. var offset = 0;
  88342. for (var i = 0; i < result.length; ++i) {
  88343. if ((i + 1) % 4 === 0) {
  88344. result[i] = 1;
  88345. }
  88346. else {
  88347. result[i] = buffer[offset++] * factor;
  88348. }
  88349. }
  88350. }
  88351. return result;
  88352. };
  88353. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  88354. var _this = this;
  88355. var attributes = primitive.attributes;
  88356. if (!attributes) {
  88357. throw new Error(context + ": Attributes are missing");
  88358. }
  88359. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  88360. // TODO: handle other primitive modes
  88361. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  88362. }
  88363. var vertexData = new BABYLON.VertexData();
  88364. var numRemainingAttributes = Object.keys(attributes).length;
  88365. var _loop_3 = function (attribute) {
  88366. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  88367. if (!accessor) {
  88368. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88369. }
  88370. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88371. switch (attribute) {
  88372. case "POSITION": {
  88373. vertexData.positions = data;
  88374. break;
  88375. }
  88376. case "NORMAL": {
  88377. vertexData.normals = data;
  88378. break;
  88379. }
  88380. case "TANGENT": {
  88381. vertexData.tangents = data;
  88382. break;
  88383. }
  88384. case "TEXCOORD_0": {
  88385. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88386. break;
  88387. }
  88388. case "TEXCOORD_1": {
  88389. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88390. break;
  88391. }
  88392. case "JOINTS_0": {
  88393. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  88394. break;
  88395. }
  88396. case "WEIGHTS_0": {
  88397. //TODO: need to add support for normalized weights.
  88398. vertexData.matricesWeights = data;
  88399. break;
  88400. }
  88401. case "COLOR_0": {
  88402. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  88403. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  88404. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  88405. mesh.hasVertexAlpha = hasVertexAlpha;
  88406. }
  88407. break;
  88408. }
  88409. default: {
  88410. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88411. break;
  88412. }
  88413. }
  88414. if (--numRemainingAttributes === 0) {
  88415. if (primitive.indices == null) {
  88416. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  88417. for (var i = 0; i < vertexData.indices.length; i++) {
  88418. vertexData.indices[i] = i;
  88419. }
  88420. onSuccess(vertexData);
  88421. }
  88422. else {
  88423. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  88424. if (!indicesAccessor) {
  88425. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  88426. }
  88427. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  88428. vertexData.indices = data;
  88429. onSuccess(vertexData);
  88430. });
  88431. }
  88432. }
  88433. });
  88434. };
  88435. var this_3 = this;
  88436. for (var attribute in attributes) {
  88437. _loop_3(attribute);
  88438. }
  88439. };
  88440. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  88441. var primitives = mesh.primitives;
  88442. var targets = primitives[0].targets;
  88443. if (!targets) {
  88444. return;
  88445. }
  88446. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  88447. var primitive = primitives_2[_i];
  88448. if (!primitive.targets || primitive.targets.length != targets.length) {
  88449. throw new Error(context + ": All primitives are required to list the same number of targets");
  88450. }
  88451. }
  88452. var morphTargetManager = new BABYLON.MorphTargetManager();
  88453. node.babylonMesh.morphTargetManager = morphTargetManager;
  88454. for (var index = 0; index < targets.length; index++) {
  88455. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  88456. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  88457. }
  88458. };
  88459. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  88460. var morphTargetManager = node.babylonMesh.morphTargetManager;
  88461. if (!morphTargetManager) {
  88462. return;
  88463. }
  88464. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  88465. var numTargets = morphTargetManager.numTargets;
  88466. for (var index = 0; index < numTargets; index++) {
  88467. var vertexData = new BABYLON.VertexData();
  88468. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88469. var primitive = _a[_i];
  88470. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  88471. }
  88472. if (!vertexData.positions) {
  88473. throw new Error(context + ": Positions are missing");
  88474. }
  88475. var target = morphTargetManager.getTarget(index);
  88476. target.setPositions(vertexData.positions);
  88477. target.setNormals(vertexData.normals);
  88478. target.setTangents(vertexData.tangents);
  88479. }
  88480. });
  88481. };
  88482. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  88483. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  88484. var _loop_4 = function (primitive) {
  88485. var targets = primitive.targets;
  88486. primitive.targetsVertexData = new Array(targets.length);
  88487. var _loop_5 = function (index) {
  88488. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  88489. primitive.targetsVertexData[index] = vertexData;
  88490. if (--numRemainingTargets === 0) {
  88491. onSuccess();
  88492. }
  88493. });
  88494. };
  88495. for (var index = 0; index < targets.length; index++) {
  88496. _loop_5(index);
  88497. }
  88498. };
  88499. var this_4 = this;
  88500. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88501. var primitive = _a[_i];
  88502. _loop_4(primitive);
  88503. }
  88504. };
  88505. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  88506. var targetVertexData = new BABYLON.VertexData();
  88507. var numRemainingAttributes = Object.keys(attributes).length;
  88508. var _loop_6 = function (attribute) {
  88509. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  88510. if (!accessor) {
  88511. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88512. }
  88513. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88514. // glTF stores morph target information as deltas while babylon.js expects the final data.
  88515. // As a result we have to add the original data to the delta to calculate the final data.
  88516. var values = data;
  88517. switch (attribute) {
  88518. case "POSITION": {
  88519. for (var i = 0; i < values.length; i++) {
  88520. values[i] += vertexData.positions[i];
  88521. }
  88522. targetVertexData.positions = values;
  88523. break;
  88524. }
  88525. case "NORMAL": {
  88526. for (var i = 0; i < values.length; i++) {
  88527. values[i] += vertexData.normals[i];
  88528. }
  88529. targetVertexData.normals = values;
  88530. break;
  88531. }
  88532. case "TANGENT": {
  88533. // Tangent data for morph targets is stored as xyz delta.
  88534. // The vertexData.tangent is stored as xyzw.
  88535. // So we need to skip every fourth vertexData.tangent.
  88536. for (var i = 0, j = 0; i < values.length; i++, j++) {
  88537. values[i] += vertexData.tangents[j];
  88538. if ((i + 1) % 3 == 0) {
  88539. j++;
  88540. }
  88541. }
  88542. targetVertexData.tangents = values;
  88543. break;
  88544. }
  88545. default: {
  88546. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88547. break;
  88548. }
  88549. }
  88550. if (--numRemainingAttributes === 0) {
  88551. onSuccess(targetVertexData);
  88552. }
  88553. });
  88554. };
  88555. var this_5 = this;
  88556. for (var attribute in attributes) {
  88557. _loop_6(attribute);
  88558. }
  88559. };
  88560. GLTFLoader.prototype._loadTransform = function (node) {
  88561. var position = BABYLON.Vector3.Zero();
  88562. var rotation = BABYLON.Quaternion.Identity();
  88563. var scaling = BABYLON.Vector3.One();
  88564. if (node.matrix) {
  88565. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  88566. matrix.decompose(scaling, rotation, position);
  88567. }
  88568. else {
  88569. if (node.translation)
  88570. position = BABYLON.Vector3.FromArray(node.translation);
  88571. if (node.rotation)
  88572. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  88573. if (node.scale)
  88574. scaling = BABYLON.Vector3.FromArray(node.scale);
  88575. }
  88576. node.babylonMesh.position = position;
  88577. node.babylonMesh.rotationQuaternion = rotation;
  88578. node.babylonMesh.scaling = scaling;
  88579. };
  88580. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  88581. var _this = this;
  88582. if (skin.babylonSkeleton) {
  88583. onSuccess();
  88584. return;
  88585. }
  88586. var skeletonId = "skeleton" + skin.index;
  88587. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  88588. if (skin.inverseBindMatrices == null) {
  88589. this._loadBones(context, skin, null);
  88590. onSuccess();
  88591. }
  88592. else {
  88593. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  88594. if (!accessor) {
  88595. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  88596. }
  88597. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88598. _this._loadBones(context, skin, data);
  88599. onSuccess();
  88600. });
  88601. }
  88602. };
  88603. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  88604. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  88605. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88606. node.babylonAnimationTargets.push(babylonBone);
  88607. return babylonBone;
  88608. };
  88609. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  88610. var babylonBones = {};
  88611. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  88612. var index = _a[_i];
  88613. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88614. if (!node) {
  88615. throw new Error(context + ": Failed to find joint " + index);
  88616. }
  88617. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  88618. }
  88619. };
  88620. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  88621. var babylonBone = babylonBones[node.index];
  88622. if (babylonBone) {
  88623. return babylonBone;
  88624. }
  88625. var boneIndex = skin.joints.indexOf(node.index);
  88626. var baseMatrix = BABYLON.Matrix.Identity();
  88627. if (inverseBindMatrixData && boneIndex !== -1) {
  88628. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  88629. baseMatrix.invertToRef(baseMatrix);
  88630. }
  88631. var babylonParentBone = null;
  88632. if (node.parent !== this._rootNode) {
  88633. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  88634. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  88635. }
  88636. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  88637. babylonBones[node.index] = babylonBone;
  88638. return babylonBone;
  88639. };
  88640. GLTFLoader.prototype._getNodeMatrix = function (node) {
  88641. return node.matrix ?
  88642. BABYLON.Matrix.FromArray(node.matrix) :
  88643. 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());
  88644. };
  88645. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  88646. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  88647. var index = indices_1[_i];
  88648. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88649. if (!node) {
  88650. throw new Error(context + ": Failed to find node " + index);
  88651. }
  88652. this._traverseNode(context, node, action, parentNode);
  88653. }
  88654. };
  88655. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  88656. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  88657. return;
  88658. }
  88659. if (!action(node, parentNode)) {
  88660. return;
  88661. }
  88662. if (node.children) {
  88663. this._traverseNodes(context, node.children, action, node);
  88664. }
  88665. };
  88666. GLTFLoader.prototype._loadAnimations = function () {
  88667. var animations = this._gltf.animations;
  88668. if (!animations) {
  88669. return;
  88670. }
  88671. for (var index = 0; index < animations.length; index++) {
  88672. var animation = animations[index];
  88673. this._loadAnimation("#/animations/" + index, animation);
  88674. }
  88675. };
  88676. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  88677. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  88678. for (var index = 0; index < animation.channels.length; index++) {
  88679. var channel = GLTFLoader._GetProperty(animation.channels, index);
  88680. if (!channel) {
  88681. throw new Error(context + ": Failed to find channel " + index);
  88682. }
  88683. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  88684. if (!sampler) {
  88685. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  88686. }
  88687. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  88688. }
  88689. };
  88690. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  88691. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  88692. if (!targetNode) {
  88693. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  88694. }
  88695. var targetPath;
  88696. var animationType;
  88697. switch (channel.target.path) {
  88698. case "translation": {
  88699. targetPath = "position";
  88700. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88701. break;
  88702. }
  88703. case "rotation": {
  88704. targetPath = "rotationQuaternion";
  88705. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88706. break;
  88707. }
  88708. case "scale": {
  88709. targetPath = "scaling";
  88710. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88711. break;
  88712. }
  88713. case "weights": {
  88714. targetPath = "influence";
  88715. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  88716. break;
  88717. }
  88718. default: {
  88719. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  88720. }
  88721. }
  88722. var inputData;
  88723. var outputData;
  88724. var checkSuccess = function () {
  88725. if (!inputData || !outputData) {
  88726. return;
  88727. }
  88728. var outputBufferOffset = 0;
  88729. var getNextOutputValue;
  88730. switch (targetPath) {
  88731. case "position": {
  88732. getNextOutputValue = function () {
  88733. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  88734. outputBufferOffset += 3;
  88735. return value;
  88736. };
  88737. break;
  88738. }
  88739. case "rotationQuaternion": {
  88740. getNextOutputValue = function () {
  88741. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  88742. outputBufferOffset += 4;
  88743. return value;
  88744. };
  88745. break;
  88746. }
  88747. case "scaling": {
  88748. getNextOutputValue = function () {
  88749. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  88750. outputBufferOffset += 3;
  88751. return value;
  88752. };
  88753. break;
  88754. }
  88755. case "influence": {
  88756. getNextOutputValue = function () {
  88757. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  88758. var value = new Array(numTargets);
  88759. for (var i = 0; i < numTargets; i++) {
  88760. value[i] = outputData[outputBufferOffset++];
  88761. }
  88762. return value;
  88763. };
  88764. break;
  88765. }
  88766. }
  88767. sampler.interpolation = sampler.interpolation || "LINEAR";
  88768. var getNextKey;
  88769. switch (sampler.interpolation) {
  88770. case "STEP": {
  88771. getNextKey = function (frameIndex) { return ({
  88772. frame: inputData[frameIndex],
  88773. value: getNextOutputValue(),
  88774. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  88775. }); };
  88776. break;
  88777. }
  88778. case "LINEAR": {
  88779. getNextKey = function (frameIndex) { return ({
  88780. frame: inputData[frameIndex],
  88781. value: getNextOutputValue()
  88782. }); };
  88783. break;
  88784. }
  88785. case "CUBICSPLINE": {
  88786. getNextKey = function (frameIndex) { return ({
  88787. frame: inputData[frameIndex],
  88788. inTangent: getNextOutputValue(),
  88789. value: getNextOutputValue(),
  88790. outTangent: getNextOutputValue()
  88791. }); };
  88792. break;
  88793. }
  88794. default: {
  88795. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  88796. }
  88797. }
  88798. ;
  88799. var keys;
  88800. if (inputData.length === 1) {
  88801. var key = getNextKey(0);
  88802. keys = [
  88803. { frame: key.frame, value: key.value },
  88804. { frame: key.frame + 1, value: key.value }
  88805. ];
  88806. }
  88807. else {
  88808. keys = new Array(inputData.length);
  88809. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  88810. keys[frameIndex] = getNextKey(frameIndex);
  88811. }
  88812. }
  88813. if (targetPath === "influence") {
  88814. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  88815. var _loop_7 = function (targetIndex) {
  88816. var morphTarget = morphTargetManager.getTarget(targetIndex);
  88817. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  88818. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  88819. babylonAnimation.setKeys(keys.map(function (key) { return ({
  88820. frame: key.frame,
  88821. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  88822. value: key.value[targetIndex],
  88823. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  88824. }); }));
  88825. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  88826. };
  88827. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  88828. _loop_7(targetIndex);
  88829. }
  88830. }
  88831. else {
  88832. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  88833. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  88834. babylonAnimation.setKeys(keys);
  88835. if (targetNode.babylonAnimationTargets) {
  88836. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  88837. var target = _a[_i];
  88838. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  88839. }
  88840. }
  88841. }
  88842. };
  88843. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  88844. if (!inputAccessor) {
  88845. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  88846. }
  88847. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  88848. inputData = data;
  88849. checkSuccess();
  88850. });
  88851. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  88852. if (!outputAccessor) {
  88853. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  88854. }
  88855. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  88856. outputData = data;
  88857. checkSuccess();
  88858. });
  88859. };
  88860. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  88861. var _this = this;
  88862. this._addPendingData(buffer);
  88863. if (buffer.loadedData) {
  88864. onSuccess(buffer.loadedData);
  88865. this._removePendingData(buffer);
  88866. }
  88867. else if (buffer.loadedObservable) {
  88868. buffer.loadedObservable.add(function (buffer) {
  88869. onSuccess(buffer.loadedData);
  88870. _this._removePendingData(buffer);
  88871. });
  88872. }
  88873. else {
  88874. if (!buffer.uri) {
  88875. throw new Error(context + ": Uri is missing");
  88876. }
  88877. buffer.loadedObservable = new BABYLON.Observable();
  88878. buffer.loadedObservable.add(function (buffer) {
  88879. onSuccess(buffer.loadedData);
  88880. _this._removePendingData(buffer);
  88881. });
  88882. this._loadUriAsync(context, buffer.uri, function (data) {
  88883. buffer.loadedData = data;
  88884. buffer.loadedObservable.notifyObservers(buffer);
  88885. buffer.loadedObservable = undefined;
  88886. });
  88887. }
  88888. };
  88889. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  88890. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  88891. if (!buffer) {
  88892. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  88893. }
  88894. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  88895. var data;
  88896. try {
  88897. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  88898. }
  88899. catch (e) {
  88900. throw new Error(context + ": " + e.message);
  88901. }
  88902. onSuccess(data);
  88903. });
  88904. };
  88905. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  88906. var _this = this;
  88907. if (accessor.sparse) {
  88908. throw new Error(context + ": Sparse accessors are not currently supported");
  88909. }
  88910. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  88911. if (!bufferView) {
  88912. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  88913. }
  88914. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  88915. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  88916. var data;
  88917. var byteOffset = accessor.byteOffset || 0;
  88918. var byteStride = bufferView.byteStride;
  88919. if (byteStride === 0) {
  88920. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  88921. }
  88922. try {
  88923. switch (accessor.componentType) {
  88924. case GLTF2.EComponentType.BYTE: {
  88925. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88926. break;
  88927. }
  88928. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88929. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88930. break;
  88931. }
  88932. case GLTF2.EComponentType.SHORT: {
  88933. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88934. break;
  88935. }
  88936. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88937. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88938. break;
  88939. }
  88940. case GLTF2.EComponentType.UNSIGNED_INT: {
  88941. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88942. break;
  88943. }
  88944. case GLTF2.EComponentType.FLOAT: {
  88945. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88946. break;
  88947. }
  88948. default: {
  88949. throw new Error(context + ": Invalid component type " + accessor.componentType);
  88950. }
  88951. }
  88952. }
  88953. catch (e) {
  88954. throw new Error(context + ": " + e);
  88955. }
  88956. onSuccess(data);
  88957. });
  88958. };
  88959. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  88960. byteOffset += data.byteOffset;
  88961. var targetLength = count * numComponents;
  88962. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  88963. return new typedArray(data.buffer, byteOffset, targetLength);
  88964. }
  88965. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  88966. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  88967. var targetBuffer = new typedArray(targetLength);
  88968. var sourceIndex = 0;
  88969. var targetIndex = 0;
  88970. while (targetIndex < targetLength) {
  88971. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  88972. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  88973. targetIndex++;
  88974. }
  88975. sourceIndex += elementStride;
  88976. }
  88977. return targetBuffer;
  88978. };
  88979. GLTFLoader.prototype._addPendingData = function (data) {
  88980. if (!this._renderReady) {
  88981. this._renderPendingCount++;
  88982. }
  88983. this._addLoaderPendingData(data);
  88984. };
  88985. GLTFLoader.prototype._removePendingData = function (data) {
  88986. var _this = this;
  88987. if (!this._renderReady) {
  88988. if (--this._renderPendingCount === 0) {
  88989. this._addLoaderPendingData(this);
  88990. this._compileMaterialsAsync(function () {
  88991. _this._compileShadowGeneratorsAsync(function () {
  88992. _this._removeLoaderPendingData(_this);
  88993. _this._renderReady = true;
  88994. _this._onRenderReady();
  88995. });
  88996. });
  88997. }
  88998. }
  88999. this._removeLoaderPendingData(data);
  89000. };
  89001. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  89002. this._loaderPendingCount++;
  89003. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  89004. var tracker = _a[_i];
  89005. tracker._addPendingData(data);
  89006. }
  89007. };
  89008. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  89009. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  89010. var tracker = _a[_i];
  89011. tracker._removePendingData(data);
  89012. }
  89013. if (--this._loaderPendingCount === 0) {
  89014. this._onComplete();
  89015. }
  89016. };
  89017. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  89018. var _this = this;
  89019. var tracker = new GLTFLoaderTracker(function () {
  89020. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  89021. onComplete();
  89022. });
  89023. this._loaderTrackers.push(tracker);
  89024. this._addLoaderPendingData(tracker);
  89025. action();
  89026. this._removeLoaderPendingData(tracker);
  89027. };
  89028. GLTFLoader.prototype._getDefaultMaterial = function () {
  89029. if (!this._defaultMaterial) {
  89030. var id = "__gltf_default";
  89031. var material = this._babylonScene.getMaterialByName(id);
  89032. if (!material) {
  89033. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  89034. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89035. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89036. material.metallic = 1;
  89037. material.roughness = 1;
  89038. }
  89039. this._defaultMaterial = material;
  89040. }
  89041. return this._defaultMaterial;
  89042. };
  89043. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  89044. var babylonMaterial = material.babylonMaterial;
  89045. // Ensure metallic workflow
  89046. babylonMaterial.metallic = 1;
  89047. babylonMaterial.roughness = 1;
  89048. var properties = material.pbrMetallicRoughness;
  89049. if (!properties) {
  89050. return;
  89051. }
  89052. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  89053. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  89054. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  89055. if (properties.baseColorTexture) {
  89056. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  89057. if (!texture) {
  89058. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  89059. }
  89060. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  89061. }
  89062. if (properties.metallicRoughnessTexture) {
  89063. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  89064. if (!texture) {
  89065. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  89066. }
  89067. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  89068. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  89069. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  89070. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  89071. }
  89072. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  89073. };
  89074. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  89075. if (material.babylonMaterial) {
  89076. assign(material.babylonMaterial, false);
  89077. return;
  89078. }
  89079. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  89080. return;
  89081. }
  89082. this._createPbrMaterial(material);
  89083. this._loadMaterialBaseProperties(context, material);
  89084. this._loadMaterialMetallicRoughnessProperties(context, material);
  89085. assign(material.babylonMaterial, true);
  89086. };
  89087. GLTFLoader.prototype._createPbrMaterial = function (material) {
  89088. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  89089. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89090. material.babylonMaterial = babylonMaterial;
  89091. };
  89092. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  89093. var babylonMaterial = material.babylonMaterial;
  89094. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  89095. if (material.doubleSided) {
  89096. babylonMaterial.backFaceCulling = false;
  89097. babylonMaterial.twoSidedLighting = true;
  89098. }
  89099. if (material.normalTexture) {
  89100. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  89101. if (!texture) {
  89102. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  89103. }
  89104. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  89105. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  89106. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  89107. if (material.normalTexture.scale != null) {
  89108. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  89109. }
  89110. }
  89111. if (material.occlusionTexture) {
  89112. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  89113. if (!texture) {
  89114. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  89115. }
  89116. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  89117. babylonMaterial.useAmbientInGrayScale = true;
  89118. if (material.occlusionTexture.strength != null) {
  89119. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  89120. }
  89121. }
  89122. if (material.emissiveTexture) {
  89123. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  89124. if (!texture) {
  89125. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  89126. }
  89127. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  89128. }
  89129. };
  89130. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  89131. var babylonMaterial = material.babylonMaterial;
  89132. var alphaMode = material.alphaMode || "OPAQUE";
  89133. switch (alphaMode) {
  89134. case "OPAQUE": {
  89135. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89136. break;
  89137. }
  89138. case "MASK": {
  89139. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  89140. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  89141. if (colorFactor) {
  89142. if (colorFactor[3] == 0) {
  89143. babylonMaterial.alphaCutOff = 1;
  89144. }
  89145. else {
  89146. babylonMaterial.alphaCutOff /= colorFactor[3];
  89147. }
  89148. }
  89149. if (babylonMaterial.albedoTexture) {
  89150. babylonMaterial.albedoTexture.hasAlpha = true;
  89151. }
  89152. break;
  89153. }
  89154. case "BLEND": {
  89155. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  89156. if (colorFactor) {
  89157. babylonMaterial.alpha = colorFactor[3];
  89158. }
  89159. if (babylonMaterial.albedoTexture) {
  89160. babylonMaterial.albedoTexture.hasAlpha = true;
  89161. babylonMaterial.useAlphaFromAlbedoTexture = true;
  89162. }
  89163. break;
  89164. }
  89165. default: {
  89166. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  89167. }
  89168. }
  89169. };
  89170. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  89171. var _this = this;
  89172. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  89173. if (!sampler) {
  89174. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  89175. }
  89176. this._loadSampler("#/samplers/" + sampler.index, sampler);
  89177. this._addPendingData(texture);
  89178. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  89179. _this._tryCatchOnError(function () {
  89180. _this._removePendingData(texture);
  89181. });
  89182. }, function (message) {
  89183. _this._tryCatchOnError(function () {
  89184. throw new Error(context + ": " + message);
  89185. });
  89186. });
  89187. if (texture.url) {
  89188. babylonTexture.updateURL(texture.url);
  89189. }
  89190. else if (texture.dataReadyObservable) {
  89191. texture.dataReadyObservable.add(function (texture) {
  89192. babylonTexture.updateURL(texture.url);
  89193. });
  89194. }
  89195. else {
  89196. texture.dataReadyObservable = new BABYLON.Observable();
  89197. texture.dataReadyObservable.add(function (texture) {
  89198. babylonTexture.updateURL(texture.url);
  89199. });
  89200. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  89201. if (!image_1) {
  89202. throw new Error(context + ": Failed to find source " + texture.source);
  89203. }
  89204. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  89205. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  89206. texture.dataReadyObservable.notifyObservers(texture);
  89207. texture.dataReadyObservable = undefined;
  89208. });
  89209. }
  89210. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  89211. babylonTexture.wrapU = sampler.wrapU;
  89212. babylonTexture.wrapV = sampler.wrapV;
  89213. babylonTexture.name = texture.name || "texture" + texture.index;
  89214. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  89215. return babylonTexture;
  89216. };
  89217. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  89218. if (sampler.noMipMaps != undefined) {
  89219. return;
  89220. }
  89221. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  89222. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  89223. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  89224. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  89225. };
  89226. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  89227. if (image.uri) {
  89228. this._loadUriAsync(context, image.uri, onSuccess);
  89229. }
  89230. else {
  89231. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  89232. if (!bufferView) {
  89233. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  89234. }
  89235. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  89236. }
  89237. };
  89238. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  89239. var _this = this;
  89240. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  89241. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  89242. return;
  89243. }
  89244. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  89245. throw new Error(context + ": Uri '" + uri + "' is invalid");
  89246. }
  89247. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  89248. _this._tryCatchOnError(function () {
  89249. onSuccess(new Uint8Array(data));
  89250. });
  89251. }, function (event) {
  89252. _this._tryCatchOnError(function () {
  89253. if (request && !_this._renderReady) {
  89254. request._lengthComputable = event.lengthComputable;
  89255. request._loaded = event.loaded;
  89256. request._total = event.total;
  89257. _this._onProgress();
  89258. }
  89259. });
  89260. }, this._babylonScene.database, true, function (request, exception) {
  89261. _this._tryCatchOnError(function () {
  89262. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  89263. });
  89264. });
  89265. this._requests.push(request);
  89266. };
  89267. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  89268. if (this._disposed) {
  89269. return;
  89270. }
  89271. try {
  89272. handler();
  89273. }
  89274. catch (e) {
  89275. BABYLON.Tools.Error("glTF Loader: " + e.message);
  89276. if (this._errorCallback) {
  89277. this._errorCallback(e.message, e);
  89278. }
  89279. this.dispose();
  89280. }
  89281. };
  89282. GLTFLoader._AssignIndices = function (array) {
  89283. if (array) {
  89284. for (var index = 0; index < array.length; index++) {
  89285. array[index].index = index;
  89286. }
  89287. }
  89288. };
  89289. GLTFLoader._GetProperty = function (array, index) {
  89290. if (!array || index == undefined || !array[index]) {
  89291. return null;
  89292. }
  89293. return array[index];
  89294. };
  89295. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  89296. // Set defaults if undefined
  89297. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  89298. switch (mode) {
  89299. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  89300. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  89301. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  89302. default:
  89303. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  89304. return BABYLON.Texture.WRAP_ADDRESSMODE;
  89305. }
  89306. };
  89307. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  89308. // Set defaults if undefined
  89309. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  89310. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  89311. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  89312. switch (minFilter) {
  89313. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  89314. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  89315. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  89316. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  89317. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  89318. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89319. default:
  89320. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89321. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89322. }
  89323. }
  89324. else {
  89325. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  89326. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  89327. }
  89328. switch (minFilter) {
  89329. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  89330. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  89331. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89332. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  89333. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  89334. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  89335. default:
  89336. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89337. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89338. }
  89339. }
  89340. };
  89341. GLTFLoader._GetNumComponents = function (context, type) {
  89342. switch (type) {
  89343. case "SCALAR": return 1;
  89344. case "VEC2": return 2;
  89345. case "VEC3": return 3;
  89346. case "VEC4": return 4;
  89347. case "MAT2": return 4;
  89348. case "MAT3": return 9;
  89349. case "MAT4": return 16;
  89350. }
  89351. throw new Error(context + ": Invalid type " + type);
  89352. };
  89353. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  89354. var _this = this;
  89355. if (this.useClipPlane) {
  89356. babylonMaterial.forceCompilation(babylonMesh, function () {
  89357. babylonMaterial.forceCompilation(babylonMesh, function () {
  89358. _this._tryCatchOnError(onSuccess);
  89359. }, { clipPlane: true });
  89360. });
  89361. }
  89362. else {
  89363. babylonMaterial.forceCompilation(babylonMesh, function () {
  89364. _this._tryCatchOnError(onSuccess);
  89365. });
  89366. }
  89367. };
  89368. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  89369. if (!this.compileMaterials || !this._gltf.materials) {
  89370. onSuccess();
  89371. return;
  89372. }
  89373. var meshes = this._getMeshes();
  89374. var remaining = 0;
  89375. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  89376. var mesh = meshes_1[_i];
  89377. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89378. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  89379. var subMaterial = _b[_a];
  89380. if (subMaterial) {
  89381. remaining++;
  89382. }
  89383. }
  89384. }
  89385. else if (mesh.material) {
  89386. remaining++;
  89387. }
  89388. }
  89389. if (remaining === 0) {
  89390. onSuccess();
  89391. return;
  89392. }
  89393. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  89394. var mesh = meshes_2[_c];
  89395. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89396. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  89397. var subMaterial = _e[_d];
  89398. if (subMaterial) {
  89399. this._compileMaterialAsync(subMaterial, mesh, function () {
  89400. if (--remaining === 0) {
  89401. onSuccess();
  89402. }
  89403. });
  89404. }
  89405. }
  89406. }
  89407. else if (mesh.material) {
  89408. this._compileMaterialAsync(mesh.material, mesh, function () {
  89409. if (--remaining === 0) {
  89410. onSuccess();
  89411. }
  89412. });
  89413. }
  89414. }
  89415. };
  89416. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  89417. var _this = this;
  89418. if (!this.compileShadowGenerators) {
  89419. onSuccess();
  89420. return;
  89421. }
  89422. var lights = this._babylonScene.lights;
  89423. var remaining = 0;
  89424. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  89425. var light = lights_1[_i];
  89426. var generator = light.getShadowGenerator();
  89427. if (generator) {
  89428. remaining++;
  89429. }
  89430. }
  89431. if (remaining === 0) {
  89432. onSuccess();
  89433. return;
  89434. }
  89435. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  89436. var light = lights_2[_a];
  89437. var generator = light.getShadowGenerator();
  89438. if (generator) {
  89439. generator.forceCompilation(function () {
  89440. if (--remaining === 0) {
  89441. _this._tryCatchOnError(onSuccess);
  89442. }
  89443. });
  89444. }
  89445. }
  89446. };
  89447. GLTFLoader.prototype._abortRequests = function () {
  89448. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  89449. var request = _a[_i];
  89450. request.abort();
  89451. }
  89452. this._requests.length = 0;
  89453. };
  89454. GLTFLoader.prototype._releaseResources = function () {
  89455. if (this._gltf.textures) {
  89456. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  89457. var texture = _a[_i];
  89458. if (texture.url) {
  89459. URL.revokeObjectURL(texture.url);
  89460. texture.url = undefined;
  89461. }
  89462. }
  89463. }
  89464. };
  89465. GLTFLoader.Extensions = {};
  89466. return GLTFLoader;
  89467. }());
  89468. GLTF2.GLTFLoader = GLTFLoader;
  89469. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  89470. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89471. })(BABYLON || (BABYLON = {}));
  89472. //# sourceMappingURL=babylon.glTFLoader.js.map
  89473. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89474. var BABYLON;
  89475. (function (BABYLON) {
  89476. var GLTF2;
  89477. (function (GLTF2) {
  89478. /**
  89479. * Utils functions for GLTF
  89480. */
  89481. var GLTFUtils = /** @class */ (function () {
  89482. function GLTFUtils() {
  89483. }
  89484. /**
  89485. * If the uri is a base64 string
  89486. * @param uri: the uri to test
  89487. */
  89488. GLTFUtils.IsBase64 = function (uri) {
  89489. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  89490. };
  89491. /**
  89492. * Decode the base64 uri
  89493. * @param uri: the uri to decode
  89494. */
  89495. GLTFUtils.DecodeBase64 = function (uri) {
  89496. var decodedString = atob(uri.split(",")[1]);
  89497. var bufferLength = decodedString.length;
  89498. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  89499. for (var i = 0; i < bufferLength; i++) {
  89500. bufferView[i] = decodedString.charCodeAt(i);
  89501. }
  89502. return bufferView.buffer;
  89503. };
  89504. GLTFUtils.ValidateUri = function (uri) {
  89505. return (uri.indexOf("..") === -1);
  89506. };
  89507. return GLTFUtils;
  89508. }());
  89509. GLTF2.GLTFUtils = GLTFUtils;
  89510. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89511. })(BABYLON || (BABYLON = {}));
  89512. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  89513. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89514. var BABYLON;
  89515. (function (BABYLON) {
  89516. var GLTF2;
  89517. (function (GLTF2) {
  89518. var GLTFLoaderExtension = /** @class */ (function () {
  89519. function GLTFLoaderExtension() {
  89520. this.enabled = true;
  89521. }
  89522. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  89523. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  89524. GLTFLoaderExtension.prototype._loadRoot = function (loader, context, root) { return false; };
  89525. GLTFLoaderExtension.prototype._loadScene = function (loader, context, scene) { return false; };
  89526. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  89527. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  89528. var _this = this;
  89529. if (!property.extensions) {
  89530. return false;
  89531. }
  89532. var extension = property.extensions[this.name];
  89533. if (!extension) {
  89534. return false;
  89535. }
  89536. // Clear out the extension before executing the action to avoid recursing into the same property.
  89537. property.extensions[this.name] = undefined;
  89538. action(context + "extensions/" + this.name, extension, function () {
  89539. // Restore the extension after completing the action.
  89540. property.extensions[_this.name] = extension;
  89541. });
  89542. return true;
  89543. };
  89544. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  89545. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  89546. };
  89547. GLTFLoaderExtension.LoadRoot = function (loader, context, root) {
  89548. return this._ApplyExtensions(function (extension) { return extension._loadRoot(loader, context, root); });
  89549. };
  89550. GLTFLoaderExtension.LoadScene = function (loader, context, scene) {
  89551. return this._ApplyExtensions(function (extension) { return extension._loadScene(loader, context, scene); });
  89552. };
  89553. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  89554. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  89555. };
  89556. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  89557. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  89558. };
  89559. GLTFLoaderExtension._ApplyExtensions = function (action) {
  89560. var extensions = GLTFLoaderExtension._Extensions;
  89561. if (!extensions) {
  89562. return false;
  89563. }
  89564. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  89565. var extension = extensions_1[_i];
  89566. if (extension.enabled && action(extension)) {
  89567. return true;
  89568. }
  89569. }
  89570. return false;
  89571. };
  89572. //
  89573. // Utilities
  89574. //
  89575. GLTFLoaderExtension._Extensions = [];
  89576. return GLTFLoaderExtension;
  89577. }());
  89578. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  89579. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89580. })(BABYLON || (BABYLON = {}));
  89581. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  89582. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89583. var BABYLON;
  89584. (function (BABYLON) {
  89585. var GLTF2;
  89586. (function (GLTF2) {
  89587. var Extensions;
  89588. (function (Extensions) {
  89589. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  89590. var MSFTLOD = /** @class */ (function (_super) {
  89591. __extends(MSFTLOD, _super);
  89592. function MSFTLOD() {
  89593. var _this = _super !== null && _super.apply(this, arguments) || this;
  89594. /**
  89595. * Specify the minimal delay between LODs in ms (default = 250)
  89596. */
  89597. _this.Delay = 250;
  89598. return _this;
  89599. }
  89600. Object.defineProperty(MSFTLOD.prototype, "name", {
  89601. get: function () {
  89602. return "MSFT_lod";
  89603. },
  89604. enumerable: true,
  89605. configurable: true
  89606. });
  89607. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  89608. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89609. for (var i = extension.ids.length - 1; i >= 0; i--) {
  89610. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  89611. if (!lodNode) {
  89612. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  89613. }
  89614. loader._traverseNode(context, lodNode, action, parentNode);
  89615. }
  89616. loader._traverseNode(context, node, action, parentNode);
  89617. onComplete();
  89618. });
  89619. };
  89620. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  89621. var _this = this;
  89622. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89623. var nodes = [node];
  89624. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  89625. var index = _a[_i];
  89626. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  89627. if (!lodNode) {
  89628. throw new Error(context + ": Failed to find node " + index);
  89629. }
  89630. nodes.push(lodNode);
  89631. }
  89632. loader._addLoaderPendingData(node);
  89633. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  89634. loader._removeLoaderPendingData(node);
  89635. onComplete();
  89636. });
  89637. });
  89638. };
  89639. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  89640. var _this = this;
  89641. loader._whenAction(function () {
  89642. loader._loadNode(context, nodes[index]);
  89643. }, function () {
  89644. if (index !== nodes.length - 1) {
  89645. var previousNode = nodes[index + 1];
  89646. previousNode.babylonMesh.setEnabled(false);
  89647. }
  89648. if (index === 0) {
  89649. onComplete();
  89650. return;
  89651. }
  89652. setTimeout(function () {
  89653. loader._tryCatchOnError(function () {
  89654. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  89655. });
  89656. }, _this.Delay);
  89657. });
  89658. };
  89659. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  89660. var _this = this;
  89661. return this._loadExtension(context, material, function (context, extension, onComplete) {
  89662. var materials = [material];
  89663. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  89664. var index = _a[_i];
  89665. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  89666. if (!lodMaterial) {
  89667. throw new Error(context + ": Failed to find material " + index);
  89668. }
  89669. materials.push(lodMaterial);
  89670. }
  89671. loader._addLoaderPendingData(material);
  89672. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  89673. loader._removeLoaderPendingData(material);
  89674. onComplete();
  89675. });
  89676. });
  89677. };
  89678. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  89679. var _this = this;
  89680. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  89681. if (index === materials.length - 1) {
  89682. assign(babylonMaterial, isNew);
  89683. // Load the next LOD when the loader is ready to render.
  89684. loader._executeWhenRenderReady(function () {
  89685. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  89686. });
  89687. }
  89688. else {
  89689. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  89690. assign(babylonMaterial, isNew);
  89691. if (index === 0) {
  89692. onComplete();
  89693. }
  89694. else {
  89695. setTimeout(function () {
  89696. loader._tryCatchOnError(function () {
  89697. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  89698. });
  89699. }, _this.Delay);
  89700. }
  89701. });
  89702. }
  89703. });
  89704. };
  89705. return MSFTLOD;
  89706. }(GLTF2.GLTFLoaderExtension));
  89707. Extensions.MSFTLOD = MSFTLOD;
  89708. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  89709. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89710. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89711. })(BABYLON || (BABYLON = {}));
  89712. //# sourceMappingURL=MSFT_lod.js.map
  89713. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89714. var BABYLON;
  89715. (function (BABYLON) {
  89716. var GLTF2;
  89717. (function (GLTF2) {
  89718. var Extensions;
  89719. (function (Extensions) {
  89720. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  89721. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  89722. function KHRMaterialsPbrSpecularGlossiness() {
  89723. return _super !== null && _super.apply(this, arguments) || this;
  89724. }
  89725. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  89726. get: function () {
  89727. return "KHR_materials_pbrSpecularGlossiness";
  89728. },
  89729. enumerable: true,
  89730. configurable: true
  89731. });
  89732. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  89733. var _this = this;
  89734. return this._loadExtension(context, material, function (context, extension, onComplete) {
  89735. loader._createPbrMaterial(material);
  89736. loader._loadMaterialBaseProperties(context, material);
  89737. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  89738. assign(material.babylonMaterial, true);
  89739. onComplete();
  89740. });
  89741. };
  89742. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  89743. var babylonMaterial = material.babylonMaterial;
  89744. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  89745. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  89746. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  89747. if (properties.diffuseTexture) {
  89748. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  89749. if (!texture) {
  89750. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  89751. }
  89752. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  89753. }
  89754. if (properties.specularGlossinessTexture) {
  89755. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  89756. if (!texture) {
  89757. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  89758. }
  89759. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  89760. babylonMaterial.reflectivityTexture.hasAlpha = true;
  89761. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  89762. }
  89763. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  89764. };
  89765. return KHRMaterialsPbrSpecularGlossiness;
  89766. }(GLTF2.GLTFLoaderExtension));
  89767. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  89768. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  89769. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89770. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89771. })(BABYLON || (BABYLON = {}));
  89772. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  89773. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89774. var BABYLON;
  89775. (function (BABYLON) {
  89776. var GLTF2;
  89777. (function (GLTF2) {
  89778. var Extensions;
  89779. (function (Extensions) {
  89780. var KHRLights = /** @class */ (function (_super) {
  89781. __extends(KHRLights, _super);
  89782. function KHRLights() {
  89783. return _super !== null && _super.apply(this, arguments) || this;
  89784. }
  89785. Object.defineProperty(KHRLights.prototype, "name", {
  89786. get: function () {
  89787. return "KHR_lights";
  89788. },
  89789. enumerable: true,
  89790. configurable: true
  89791. });
  89792. KHRLights.prototype.applyCommonProperties = function (light, lightInfo) {
  89793. if (lightInfo.color) {
  89794. light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
  89795. }
  89796. else {
  89797. light.diffuse.copyFromFloats(1, 1, 1);
  89798. }
  89799. if (lightInfo.intensity !== undefined) {
  89800. light.intensity = lightInfo.intensity;
  89801. }
  89802. else {
  89803. light.intensity = 1;
  89804. }
  89805. };
  89806. KHRLights.prototype._loadScene = function (loader, context, scene) {
  89807. return this._loadExtension(context, scene, function (context, extension, onComplete) {
  89808. if (extension.light >= 0 && loader._gltf.extensions) {
  89809. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  89810. if (lightInfo.type !== 'ambient') {
  89811. return;
  89812. }
  89813. var lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
  89814. loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
  89815. }
  89816. onComplete();
  89817. });
  89818. };
  89819. KHRLights.prototype._loadNode = function (loader, context, node) {
  89820. var _this = this;
  89821. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89822. if (extension.light >= 0 && loader._gltf.extensions) {
  89823. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  89824. var name_1 = node.name || 'Light';
  89825. var matrix = void 0;
  89826. if (node.matrix) {
  89827. matrix = BABYLON.Matrix.FromArray(node.matrix);
  89828. }
  89829. else {
  89830. matrix = BABYLON.Matrix.Identity();
  89831. }
  89832. var direction = new BABYLON.Vector3(0, 0, 1);
  89833. if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
  89834. var rotationMatrix = matrix.getRotationMatrix();
  89835. BABYLON.Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
  89836. }
  89837. var light = void 0;
  89838. if (lightInfo.type == 'directional') {
  89839. light = new BABYLON.DirectionalLight(name_1, direction, loader._babylonScene);
  89840. }
  89841. else {
  89842. var position = matrix.getTranslation();
  89843. if (lightInfo.type == 'spot') {
  89844. var angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
  89845. light = new BABYLON.SpotLight(name_1, position, direction, angle, 2, loader._babylonScene);
  89846. }
  89847. else {
  89848. light = new BABYLON.PointLight(name_1, position, loader._babylonScene);
  89849. }
  89850. }
  89851. _this.applyCommonProperties(light, lightInfo);
  89852. extension.babylonLight = light;
  89853. extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
  89854. if (node.children) {
  89855. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  89856. var index = _a[_i];
  89857. var childNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  89858. if (!childNode) {
  89859. throw new Error(context + ": Failed to find child node " + index);
  89860. }
  89861. loader._loadNode("#/nodes/" + index, childNode);
  89862. }
  89863. }
  89864. }
  89865. onComplete();
  89866. });
  89867. };
  89868. KHRLights.prototype._loadRoot = function (loader, context, root) {
  89869. return this._loadExtension(context, root, function (context, extension, onComplete) {
  89870. extension.lights.forEach(function (light, idx) {
  89871. light.index = idx;
  89872. });
  89873. onComplete();
  89874. });
  89875. };
  89876. return KHRLights;
  89877. }(GLTF2.GLTFLoaderExtension));
  89878. Extensions.KHRLights = KHRLights;
  89879. GLTF2.GLTFLoader.RegisterExtension(new KHRLights());
  89880. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89881. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89882. })(BABYLON || (BABYLON = {}));
  89883. //# sourceMappingURL=KHR_lights.js.map
  89884. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  89885. globalObject["BABYLON"] = BABYLON;
  89886. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var HighlightLayer = BABYLON.HighlightLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  89887. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };